Angular 2 - Why you cannot output an input value

It seems to me that I am missing something here, and I would like to know if there is a better way to do this.

I have a directive that basically adds a class to the parent of an input field. When loading, I need to check if the input field has a value, you would think that it will be simple ...

Now I have used several different options that include ngOnInit, AfterContentInitand AfterViewInit. But for below, I'm still on AfterContentInit:

ngAfterContentInit() {
  console.log(this.el.nativeElement); // Element Object "Value is not empty if you look inside the object."
  console.log(this.el.nativeElement.value); // = ''

  setTimeout(() => {
    console.log(this.el.nativeElement.value); // = 'The Value!'
  }, 1000);

  this.activeStateCheck(this.el.nativeElement);
}

activeStateCheck(element) {
  if (element.value !== '') {
    element.parentElement.classList.add('active');
    return true;
  }
}

I must indicate that all parameters give the same results.

The first console prints an empty string, and the second prints the actual string. In this case, this is a "Grand Tour".

My question is: how do I do this without using setTimeout?

, , . , OnInit ?

, , , , , .

. appPlaceholder:

<fieldset class="form__placeholder">
    <input type="text" 
            id="lastName" 
            formControlName="lastName" 
            appPlaceholder>
    <label for="lastName"
           class="form__placeholder--label">
      Lastname:
    </label>
</fieldset>
+4
4

, , , . "active" ,

<div [ngClass]={'active': groupForm.get('name').value !== ''}>
  <input formControlName="lastName">
</div>

!== '', .

- , formControlName , @Input() formControlName;, , formGroup . , , DOM, ( HostBinding). , / .

+5

, 1 , , , ?

ng-container , .

-

<ng-container *ngIf="finishLoading">

    // ......

    <fieldset class="form__placeholder">
        <input type="text" 
                id="lastName" 
                formControlName="lastName" 
                appPlaceholder>
        <label for="lastName"
               class="form__placeholder--label">
          Lastname:
        </label>
    </fieldset>

    // ......

</ng-container>

true

this.finishLoading = true;

, .

+1

valueChanges :

this.myForm.get('lastName').valueChanges.subscribe(val => {
     console.log(val);
     this.activeStateCheck(val);
});  

, OnInt AfterViewInit.

:

https://alligator.io/angular/reactive-forms-valuechanges/

0

To ensure that when the value is reached, you must subscribe to the HTMLInputElement I / O event emitter. In doing so, you will never have race conditions . I think this is good for your purposes.

ngOnInit() {  
  fromEvent(this.el.nativeElement, 'input').subscribe((event) => activeStateCheck(event.target.value);
}

activeStateCheck(value) {
  if (value !== '') {
    this.el.element.parentElement.classList.add('active');
    return true;
  }
}

Hope this helps.

0
source

Source: https://habr.com/ru/post/1693642/


All Articles