Робота з компонентами

ng-content

ng-content - це елемент, що дозволяє передати HTML контент з батьківського компонента в дочірній.

<ng-content></ng-content>

Приклад:

app.component.html
<app-footer>
  <h2>Footer title</h2>
</app-footer>
footer.component.html
<footer>
  <ng-content></ng-content>
</footer>

Проте стилізуємо переданий HTML контент в батьківському компоненті.

Взаємодія між компонентами

@Input() - дозволяє прив'язати дані з батьківського елемента дочірньому.

app.component.html
<app-header [title]="headerTitle"></app-header>
header.component.ts
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() - дозволяє передати подію з дочірнього елемента батьківському.

header.component.ts
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.component.html
<app-header (headerText)="onHeaderTitle($event)"></app-header>
app.component.ts
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?