美文网首页web前端
angular-viewChild和viewChildren

angular-viewChild和viewChildren

作者: 姜治宇 | 来源:发表于2020-11-26 20:08 被阅读0次

    viewChild主要是父组件提取子组件信息的。废话不多说,直接上代码。
    还是新建几个指令做测试:

    ng g component components/parent
    ng g component components/son
    

    viewChild

    parent.component.html:

    <app-son #son1 uname="jerry"></app-son>
    <app-son #son2 uname="tom"></app-son>
    
    <ng-template #test>
        <div>这是一个测试</div>
    </ng-template>
    

    parent.component.ts:

    import { Component, OnInit,ViewChild } from '@angular/core';
    
    @Component({
      selector: 'app-parent',
      templateUrl: './parent.component.html',
      styleUrls: ['./parent.component.scss']
    })
    export class ParentComponent implements OnInit {
      @ViewChild('son1') son:any;
      @ViewChild('test') test:any;
      constructor() { }
    
      ngOnInit(): void {
      }
      ngAfterViewInit() {
        console.log('子组件的uname:',this.son.uname);//获取子组件的uname
        console.log('ng-template内容:',this.test.elementRef);//获取ng-template信息
      }
    
    }
    
    

    viewChildren

    如果是筛选出多个子组件,就要用到viewChildren。
    parent.component.ts:

    import { Component, OnInit,ViewChildren,QueryList } from '@angular/core';
    
    import { SonComponent } from '../son/son.component'
    @Component({
      selector: 'app-parent',
      templateUrl: './parent.component.html',
      styleUrls: ['./parent.component.scss']
    })
    export class ParentComponent implements OnInit {
      @ViewChildren(SonComponent) sons:QueryList<SonComponent>;
      constructor() { }
    
      ngOnInit(): void {
      }
      ngAfterViewInit() {
        this.sons.forEach(item=>{
          console.log(item.uname);
        })
      }
    
    }
    

    viewChild和contentChild的区别

    viewChild是从父组件提取子组件的信息,而contentChild是从插槽内容中提取组件的信息。
    或者换一种说法,viewChild是提取节点本身的信息(view),而contentChild是提取节点包裹的内容(content)。

    相关文章

      网友评论

        本文标题:angular-viewChild和viewChildren

        本文链接:https://www.haomeiwen.com/subject/sxyziktx.html