angular组件开发之-ng-content,contentChild,ng-container,ng-templeate,viewChild详解-第二篇

@contentChild

上一篇,我们讲了ng-content的用法,angular提供了contentChild来获取ng-content里面的内容,
@ContentChild装饰器(selector);

selector:组件名字或者模板变量,不能是简单的div、img这种原始标签!

接着上一篇的father.component.ts,定义两个成员变量

appChild:
@ContentChild(AppChild,{static:false})appChild: AppChild
意思是从father组件内容投影ng-content钟查找出AppChild组件。

img:
@ContentChild('img',{static:false})img: any
意思是从father组件内容投影ng-content中查找出img模板变量,注意不是img标签

angular组件开发之-ng-content,contentChild,ng-container,ng-templeate,viewChild详解-第二篇_第1张图片

使用app-father,可以看到app-father标签内使用了app-child组件,并且在img标签上定义了模板变量#img,这样当这些内容投影到app-father组件时,我们通过contentChild就可以获取到:
angular组件开发之-ng-content,contentChild,ng-container,ng-templeate,viewChild详解-第二篇_第2张图片

ngAfterContentInit

生命周期钩子函数,指的是组件内所有的投影内容即ng-content初始化完成了。上面我们在该方法中打印此时的father组件,内容如下:
angular组件开发之-ng-content,contentChild,ng-container,ng-templeate,viewChild详解-第二篇_第3张图片
两个成员变量appChild,img,类型分别是AppChild类,与ElementRef。

获取到投入内容后,我们就可以调用投影的一些方法
调用appChild组件的getItemNameList()

angular组件开发之-ng-content,contentChild,ng-container,ng-templeate,viewChild详解-第二篇_第4张图片

viewChild

与contentChild类似,区分是
contentChild:获取投影里的子内容
viewChild:直接获取组件内定义的子内容

接下里,我们在father.component的模板中直接引入app-child

先来看app-child,定义一个输入型属性,然后循环展示

import {Component, OnInit, Input} from '@angular/core';

@Component({
    selector:'app-child',
    template:`
           
  • { {item.name}}
` }) export class AppChild implements OnInit{ @Input() items:{ name:string value:any }[] constructor(){} ngOnInit(){} getItemNameList(){ return this.items.map((item)=>item.name); } }

father.component.ts中引入,并且定义成员变量viewAppChild

angular组件开发之-ng-content,contentChild,ng-container,ng-templeate,viewChild详解-第二篇_第5张图片
打印结果:

angular组件开发之-ng-content,contentChild,ng-container,ng-templeate,viewChild详解-第二篇_第6张图片
好了,报错,因为啥知道不?因为我们的viewAppChild是通过viewChild获取,contentInit指的是投影初始化完成,此时我们的视图初始化还没有完成,angular提供了ngAfterViewInit来监听视图完成

angular组件开发之-ng-content,contentChild,ng-container,ng-templeate,viewChild详解-第二篇_第7张图片

这样就OK。

viewChild与contentChild传入的参数是一样的,都是组件名或模板变量。

你可能感兴趣的:(angular,angular,viewChild,contentChild)