angular 元件互動

2022-05-28 12:54:11 字數 1574 閱讀 8191

angular是以元件化的形式來實現,因而元件互動是極為基礎且重要的,下面對其元件之間的互動方式一一介紹。

1. 通過輸入型繫結把資料從父元件傳到子元件。

3.父元件監聽子元件的事件

4. 父元件與子元件通過本地變數互動

注:用本地變數可使用在父元件模板裡面來讀取子元件的屬性或者使用其方法;

5. 父元件呼叫@viewchild()

4>侷限性:只能在元件模板裡面使用子元件的小戶型或方法,但是父元件的類並不能使用;

當父元件類需要這種訪問時,可以把子元件作為 viewchild,注入到父元件裡面。

parent:

@viewchild

(countdowntimercomponent)

privatechildcomponent:childcomponent;

start()

6. 父元件和子元件通過服務來通訊

service:

private a = new subject();

private b = new subject();

ac = this.a.asobservable();

bc = this.b.asobservable();

calla(messagea: string){

this.a.next(messagea);

callb(messageb: string){

this.b.next(messageb);

parent:

@component({

providers: [service]

nbr = 1;

subscription: subscription;

constructor(private service: service){

this.subscription = service.ac.subscribe(message => {

console.log(message);

add() {

this.service.callb(nbr);

child:

constructor(private service: service){

this.subscription = service.bc.subscribe(message => {

console.log(message);

add(){

this.service.calla("child call a");

這樣子父元件都可通過自己類中的方法使用服務來影響到另乙個元件

Angular元件之間的互動

通過輸入型繫結把資料從父元件傳到子元件 child.component.ts export class childcomponent implements oninit ngoninit void child.component.html style background color 749f84 ...

Angular元件之間常用互動方法

1.通過輸入型繫結把資料從父元件傳到子元件 child.component.ts export class childcomponent implements oninit ngoninit void child.component.html style background color 749f8...

angular子父元件之間的互動

子元件傳遞的是乙個字串,可以根據相應的需求定義成如數字,陣列,物件等型別。import from angular core output private childouter new eventemitter output private childouter2 new eventemitter s...