Angular 学习日记 - 8 - 生命周期(2)

文章详细解释了Angular中的ViewChild和ContentChild指令在组件生命周期中的行为,尤其是在afterViewInit和afterContentInit阶段的渲染。通过实例展示了如何在父组件中使用这两个指令获取子组件的元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于ViewChild的扩展

被@ViewChild 修饰的属性直到 afterViewInit()时才会渲染出来。

<!-- <div class="panel panel-primary"> -->
  <div class="panel-heading" #heading>{{ element.name }}</div>
<!--  <div class="panel-body">
    <p>
      <strong *ngIf="element.no % 2 === 0" style="color: red">{{
        element.content
      }}</strong>
      <em *ngIf="element.no % 2 === 1" style="background-color: red">{{
        element.content
      }}</em>
    </p>
  </div>
</div>
-->
export class ServerComponent {
  @ViewChild('heading', { static: true }) header: ElementRef;
  
  ngOnInit(): void {
    console.log('OnInit Called');
    console.warn('heading :', this.header.nativeElement.textContent);
  }

  ngAfterViewInit() {
    console.log('AfterViewInit Called');
    console.warn('heading :', this.header.nativeElement.textContent);
  }
}

关于ContentChild的扩展

被@ContentChild 修饰的属性直到 afterContentInit()时才会渲染出来。

子组件代码

<div class="panel panel-primary">
  <div class="panel-heading" #heading>{{ element.name }}</div>
  <div class="panel-body">
    <ng-content></ng-content>
  </div>
</div>
export class ServerComponent {
  @ViewChild('heading', { static: true }) header: ElementRef;
  @ContentChild('paragraphContent', { static: true }) paragraph: ElementRef;

  ngOnInit(): void {
    console.log('OnInit Called');
    console.warn('heading :', this.header.nativeElement.textContent);
    console.warn('paragraph :', this.paragraph.nativeElement.textContent);
  }

  ngAfterContentInit() {
    console.log('AfterContentInit Called');
    console.warn('paragraph :', this.paragraph.nativeElement.textContent);
  }

  ngAfterViewInit() {
    console.log('AfterViewInit Called');
    console.warn('heading :', this.header.nativeElement.textContent);
  }
}

 父组件代码

<!-- <div *ngFor="let server of servers"> 
    <app-server [element]="server" [name]="server.name"> -->
      <p #paragraphContent>
<!--    <strong *ngIf="server.no % 2 === 0" style="color: red">{{
          server.content
        }}</strong>
        <em *ngIf="server.no % 2 === 1" style="background-color: red">{{
          server.content
        }}</em>
      </p>
    </app-server>
  </div> -->

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值