[英]Angular4 @Input() to pass value from parent component to child component
我在App component.html中有一個像這樣的代碼。
<form>
<input #box1 (blur)="onKey1(box1.value)" type="text" name="username">
<p>{{box1.value}}</p>
</form>
在AppComponent.ts中我有這樣的代碼。
import { Component } from '@angular/core';
import { OnInit } from '@angular/core/src/metadata/lifecycle_hooks';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent{
type:string;
constructor() { }
onKey1(value:string)
{
this.type=value;
}
}
現在我創建了一個名為MyComponent3的組件。 在該組件中,我想從app組件中檢索數據.MyComponent3.html的代碼如下:
<p>{{type}}</p>
在MyComponent3.ts中,我有以下代碼。
import { Component, OnInit, ViewEncapsulation,Input } from '@angular/core';
@Component({
selector: 'app-my-component3',
templateUrl: './my-component3.component.html',
styleUrls: ['./my-component3.component.css'],
encapsulation: ViewEncapsulation.None
})
export class MyComponent3Component implements OnInit {
@Input() type;
ngOnInit() {
}
}
但是在輸出中,值沒有從AppComponent傳遞到My Component3。
應該在其中提及您要傳遞給子組件的任何屬性。 您可以使用@input和html傳遞給子組件,如下所示,
<app-my-component3 [type]="type"></app-my-component3>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.