Робота з компонентами
ng-content
ng-content - це елемент, що дозволяє передати HTML контент з батьківського компонента в дочірній.
<ng-content></ng-content>
Приклад:
<app-footer>
<h2>Footer title</h2>
</app-footer>
<footer>
<ng-content></ng-content>
</footer>
Взаємодія між компонентами
@Input() - дозволяє прив'язати дані з батьківського елемента дочірньому.
<app-header [title]="headerTitle"></app-header>
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
@Input() title: string;
constructor() {
}
ngOnInit() {}
}
Прив'язка до події в дочірньому елементі
@Output() - дозволяє передати подію з дочірнього елемента батьківському.
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
@Output() headerText = new EventEmitter<string>();
constructor() {
}
ngOnInit() {
this.someEvent();
}
private someEvent() {
this.headerText.emit('Some text in header');
}
}
<app-header (headerText)="onHeaderTitle($event)"></app-header>
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
constructor() {
}
onHeaderTitle(text: string): void {
console.log(text);
}
}
Життєвий цикл компонента
Після створення компонента фреймворк Angular викликає у цього компонента ряд методів, які представляють різні етапи життєвого циклу.
Метод
Викликається
ngOnInit()
при ініціалізації компонента.
ngOnDestroy()
перед видаленням компонента.
ngOnChanges()
перед методом ngOnInit() та при зміні властивостей в прив'язці.
Last updated
Was this helpful?