I come back after a long timeout because my relocation to Cyprus. In this video I’ll remind you about last discussing lifecycle angular component hooks. Also we’ll consider the special decorators for getting access to child component from parent
Angular has termines View and Content. Note, that View depends on Content. Content is all betweeen openning and closing component tag. View includes component template (it also may be child components). For rendering content in the child component the special directive ng-content is using. Angular has special hooks ngAfterViewInit, ngAfterViewChecked, ngAfterContent and ngAfterContentChecked to handle init and check View and Content of component.
To get access to child component use @ViewChild() decorator. Also you can get access to component content with using @ContentChild() decorator.
To get access to child component use @ViewChild() decorator. Also you can get access to component content with using @ContentChild() decorator.
Code lesson (app.component.ts)
import { AfterContentChecked, AfterContentInit } from '@angular/core';
import { AfterViewInit, Component, ContentChild, ViewChild } from '@angular/core';
import { UserComponent } from './user/user.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements AfterViewInit, AfterContentInit {
user = 'ang-app';
@ViewChild(UserComponent) userCmp: UserComponent | undefined;
@ContentChild(UserComponent) userCmpCnt: UserComponent | undefined;
changeUserName() {
this.user = 'Kamil Abzalov';
}
ngAfterViewInit(): void {
console.log(this.userCmp);
}
ngAfterContentInit() {
console.log(this.userCmpCnt);
}
}
Code lesson (app.component.html)
<!-- View: шаблон + дочерки -->
<!-- Content (инициализируется до view) -->
<button (click)="changeUserName()">Change User name</button>
<app-user [user]="user">
<h1>Hello {{user}}</h1>
</app-user>
Code lesson (user.component.html)
{{user}}
{{admin}}
<ng-content></ng-content>
0 Comments