angular - Pochopenie @input - z rodiča na dieťa
Snažím sa naučiť Angular a teraz som na fáze @Input.
Mám hlavnú aplikáciu a podkomponent. V app.component.ts mám testovaciu premennú. Chcem túto premennú odovzdať z app.component.ts do child.component.ts.
// app.component.ts:
export class AppComponent {
test = 10;
}
// child.component.ts:
export class ChildComponent {
@Input() fromParent: number;
childVar = fromParent + 5;
show() {
console.log(this.childVar);
} //this should to show 15 in console...
}
Teraz, ako to môžem urobiť?
Odpoveď č. 1
Nižšie nájdete príklad, ktorý ilustruje mechanizmus umožňujúci rodičovskej komponente viazať vlastnosti, ku ktorým môže mať prístup detská komponenta.
Šablóna nadradenej komponenty: parent.component.html
<child-component
[fromParent]="fromParent">
</child-component>
Rodičovská trieda komponentu: parent.component.ts
export class ParentComponent {
fromParent: string = 'String from parent';
}
Trieda komponentu dieťaťa: child.component.ts
import { Component, Input } from '@angular/core';
//...
export class ChildComponent {
@Input() fromParent: string;
}
Šablóna komponentu dieťaťa: child.component.html
String from parent: {{ fromParent }}
Odpoveď č. 2
Vo vašom app.component.html voláte selector vášho podriadeného komponentu (predpokladajme, že je to child-app) :
<child-app></child-app>
Potom k tomu pridajte to, čo je deklarované ako @input(), a viažte to na hodnotu v AppComponent (čo je test):
<child-app [fromParent]="test" ></child-app>
Nakoniec by ste mali svoj útržok prepracovať na:
****child.component.ts:****
export class ChildComponent { // Here is not AppComponent
@Input() fromParent: number;
childvar: number;
show() {
this.childVar = this.fromParent + 5; // this op should be inside a method
console.log(this.childVar);
} //this should to show 15 in console...
}
