0

I use ViewChild in the following way:

@Component({
    selector: 'demo',
    template: `<input type="text" #firstnameCtrl [(ngModel)]="firstname" />`
})
export class DemoComponent {
    public firstname: string;
    @ViewChild('firstnameCtrl') firstElementCtrl: ElementRef;
}

If someone changed in the template the exported variable #firstnameCtrl to #firstnameElement the application is broken, but no compiler was raised (also not in AOT).

So is there a prefered approach to bind ViewChild in a saver way?

Thanks!

Martin Schagerl
  • 583
  • 1
  • 7
  • 19

1 Answers1

0

https://angular.io/api/core/ViewChild shows an example of binding a child via an object. Copying the code here, in case link becomes invalid in future:

You can use ViewChild to get the first element or the directive matching the selector from the view DOM. If the view DOM changes, and a new child matches the selector, the property will be updated.

View queries are set before the ngAfterViewInit callback is called.

Metadata Properties:

selector - the directive type or the name used for querying. read - read a different token from the queried elements.

import {Component, Directive, Input, ViewChild} from '@angular/core';
@Directive({selector: 'pane'})
export class Pane {
   @Input() id: string;
}

@Component({
  selector: 'example-app',
  template: `
    <pane id="1" *ngIf="shouldShow"></pane>
    <pane id="2" *ngIf="!shouldShow"></pane>

    <button (click)="toggle()">Toggle</button>

    <div>Selected: {{selectedPane}}</div> 
  `,
})
export class ViewChildComp {
  @ViewChild(Pane)
  set pane(v: Pane) {
    setTimeout(() => { this.selectedPane = v.id; }, 0);
  }
  selectedPane: string = '';
  shouldShow = true;
  toggle() { this.shouldShow = !this.shouldShow; }
}
Adam Pine
  • 387
  • 2
  • 7
  • This is not 100% a clean solution, because if the id prperty is changed, then the application is broken without any compiler errors. So I need a way simular to FormControl (e.q. ). Because I am using template drive approach, I need a solution with ViewChild. – Martin Schagerl Jun 04 '18 at 18:27