首頁 > web前端 > js教程 > 主體

Angular父子元件間怎麼進行通訊?父子傳值的方式淺析

青灯夜游
發布: 2021-08-10 10:02:07
轉載
1828 人瀏覽過

Angular父子元件間怎麼進行通訊?這篇文章跟大家介紹Angular父子元件傳值方式。

Angular父子元件間怎麼進行通訊?父子傳值的方式淺析

透過Input和Ouput傳值

#父元件:html和ts

<app-liftcycle [name]="name" (changeName)="changeName($event)"></app-liftcycle>
登入後複製
public name: string = "jack";
public changeName(value: string) {
    this.name = value;
}
登入後複製

子元件:html和ts

<div (click)="emit()">{{name}}</div>
登入後複製
import { Component, Input, EventEmitter, Output } from &#39;@angular/core&#39;;
@Input() name: string;
@Output() changeName: EventEmitter<string> = new EventEmitter<string>();
public emit() {
    this.changeName.emit("修改name属性");
}
登入後複製

【相關教學推薦:《angular教程》】

透過setter監聽屬性的變化

##父元件同上,子元件:

private _name: string = "";
@Input() 
public get name(): string {
    return this._name;
}
public set name(value: string) {
    this._name = value + "定义结构";
}
登入後複製

透過ngOnChanges鉤子函式監聽輸入屬性的變化

ngOnChanges在監聽多個屬性的時候,要比setter的方式簡單一些。

@Input() name: string;
ngOnChanges(changes: SimpleChanges): void {
    (({name}) => {
        console.log(name.currentValue,name.previousValue);
    })(changes);
}
登入後複製

父元件html中透過模板變數呼叫子元件的方法和屬性。

模板變數取得了子元件的一個參考。 父元件:

<app-liftcycle #child></app-liftcycle>
<button (click)="child.childFn()">按钮</button>
登入後複製

子元件:

public childFn() {
    console.log("通过模板变量调用子组件中的方法");
}
登入後複製

父元件透過ViewChild取得子元件實例

<app-liftcycle [name]="name" (changeName)="changeName($event)" #child></app-liftcycle>
<button (click)="childFn()">childFn</button>
登入後複製
@ViewChild("child") child: LiftcycleComponent;
public childFn(): void {
    this.child.childFn();
}
登入後複製

透過service進行通訊

service:

import { Subject } from &#39;rxjs&#39;;
import { Injectable } from &#39;@angular/core&#39;;

@Injectable({
    providedIn: &#39;root&#39;
})
export class CommunService {

    constructor() {}
    public commun = new Subject<string>();
    communSend() {
        this.commun.next("send");
    }
}
登入後複製

父元件:

constructor(private commun: CommunService) { }
public send(): void {
    this.commun.communSend();
}
登入後複製

子元件:

constructor(private commun: CommunService) { 
    this.commun.commun.subscribe((value) => {console.log(value)});
}
登入後複製

父元件傳遞方法

父元件透過屬性傳遞給子元件方法,子元件進行調用,一般不推薦,React採用這種通訊方式。 可能是基於this的綁定錯綜複雜,所以angular不太推薦。 React Hooks的出現也有一部分原因 是class類的this錯綜複雜。 父元件:

<app-liftcycle [send]="send.bind(this)"></app-liftcycle>
登入後複製
public name: string = "jack";
public send(): void {
    console.log(this.name);
}
登入後複製

子元件:

<button (click)="childSend()">childSend</button>
登入後複製
@Input() send: Function;
public childSend() {
    this.send();
}
登入後複製
更多程式相關知識,請造訪:

程式設計影片! !

以上是Angular父子元件間怎麼進行通訊?父子傳值的方式淺析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:juejin.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!