有兩個組件,一個是頂部面板(父組件)和顯示(子組件)。我試著輸入一些值,如名字、姓氏、電子郵件,然后點擊按鈕,在子組件空間顯示輸入的值(例如:Andy John [email protected])。你能不能幫助我,在點擊按鈕的時候,如何在父組件和子組件之間進行互動。
這里是示例
uj5u.com熱心網友回復:
你可以像這樣給子組件添加屬性:
你可以像這樣給子組件添加屬性。
import { Component } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css'] 。
})
export class ChildComponent implements OnInit {
@Input() firstname: string;
}
像這樣從父級的HTML模板中把它們傳達下去:
<app-child [firstname]="firstname"></app-child>
然后像這樣在孩子的HTML模板中顯示它們:
Hello {{firstname}}.
uj5u.com熱心網友回復:
在你的代碼中,有一些錯誤
更多細節請參考 :
-> https://angular.io/guide/inputs-outputs
-> https://angular.io/guide/component-interaction
為了您的目的,請查看您編輯的例子。https://stackblitz.com/edit/angular7-communication-between-components-coqvnq?file=src/app/child/child.component.html
使用@Input指令
解釋一下
在這里,父組件被改變為帶有formcontrols -firstname, lastname, email等的表單,當點擊按鈕時,表單的值被使用.push添加到array-parentVar。 在這里,在parent.componet.html中,我們已經添加了childcomponet指令
。<app-child [parentOutputVar]="parentVar"></app-child>
parent.component中的parentVar將資料作為輸入發送給app-child([parentOutputVar]="parentVar")。
資料將使用結構指令顯示 -ngIf &ngFor
uj5u.com熱心網友回復:
為了在父組件和子組件之間共享資料,我們使用@Input()和@Output()裝飾器。
第一步是建立父組件和子組件之間的層次結構。<parent-component>為<child-component>
在所討論的兩個裝飾器@Input和@Output中,@Input裝飾器讓父組件更新子組件中的資料,@Output裝飾器讓子組件發送資料給父組件。
你的要求是在點擊submit按鈕時從父組件向子組件發送資料。為此,你首先需要配置你的子組件,使之成為
- 在你的child.component.ts中。
添加
@Input()并用它來裝飾屬性,如下所示,
@Input() formData: any = [] 。
- 在你的parent.component.ts。
使用子選擇器
<app-child [formData] = "formValue"></app-child>作為其模板中的指令。在這里,我們使用屬性系結,將父類的formValue屬性系結到子類的formData屬性。
TLDR;
請找到StackBlitz專案,說明父子資料通信。
在這里,我已經更新了您提供的示例,以便在您的子組件中顯示在表單中輸入的值,使用Input()裝飾器。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/323541.html
標籤:
