angularangular6angular7parent-childangular-input

unable to access template ref variables


At child.ts, I have a function onButtonClicked which modify revertDisabled from true to false.

Having an issue where the template reference variable at parent.html is still getting value true for revertDisabled variable, even after the user have executed function onButtonClicked() at child.ts which has changed revertDisabled value from true to false.

I have tried solve it by adding @input at parent.ts but still could not access the changed value of revertDisabled .

parent.html

<button type="button" [disabled]="interface.revertDisabled"></button>
<interface-settings #interface></interface-settings>

child.ts (interface-settings.ts)

this.revertDisabled = true;

onButtonClicked() {
  this.revertDisabled = false;
}

Solution

  • Yes parent won't pickup a value this way. Via template variable you can execute a child's method as described here: https://angular.io/guide/component-interaction#parent-interacts-with-child-via-local-variable

    But the guide also says it explicitly:

    The parent component cannot data bind to the child's start and stop methods nor to its 'seconds' property.

    You can accomplish what you need using @Output and the pattern described here: https://angular.io/guide/component-interaction#parent-listens-for-child-event

    Basically:

     //child.ts (interface-settings.ts)
    
     @Output() revertDisabled = new EventEmitter<boolean>();
    
     onButtonClicked() {
        this.revertDisabled.emit(false);
     }
    

    then:

     //  parent.html
     <button #parentButton type="button"></button>
     <interface-settings (revertDisabled)="parentButton.disabled=false"></interface-settings>