*ngIf and local template variables

后端 未结 1 1271
有刺的猬
有刺的猬 2020-11-27 07:28

Could someone please explain what\'s behind the following behavior?

Say we have an Angular 2 component that has a _model object. Then in the template we

相关标签:
1条回答
  • 2020-11-27 07:56

    We can reference a local template variable on the same element, on a sibling element, or on any child elements. -- ref

    *ngIf becomes/expands to

    <template [ngIf]="_model">
        <input type="text" class="form-control" required [(ngModel)]="_model.firstName"
         ngControl="test1" #myInput>
    </template>
    

    So local template variable #myInput can only be referenced inside the template block (i.e., sibling and/or child elements). Hence you would have to put any HTML that wants to reference the local template variable inside the template:

    <template [ngIf]="_model">
       <input type="text" class="form-control" required [(ngModel)]="_model.firstName"
        ngControl="test1"  #myInput >
       <br>Class (this works): {{myInput?.className}}
    </template>
    

    Plunker


    If you need to show something outside the template block related to the input, use @ViewChildren('myInput') list:QueryList<ElementRef> and then subscribe to changes:

    ngAfterViewInit() {
       this.list.changes.subscribe( newList =>
          console.log('new list size:', newList.length)
       )
    }
    

    See more QueryList methods in the API doc.

    0 讨论(0)
提交回复
热议问题