[英]Access to the parent value from child component [Angular]
AppComponent(父級)具有主頁(版式)和頁面計數器:
export class AppComponent {
counter = '1/3';
}
<div class="counter">
{{counter}}
</div>
頁面內容還由兩個組件(子組件)負責。 從子組件中,需要有權訪問父值(計數器)。
其中之一:
import {AppComponent} from '../app.component';
export class Page1Component {
app: AppComponent;
}
SomeEvent($event) {
this.app.counter='2/3';
}
<div class="content">
...
</div>
事件發生后,我得到一個錯誤:“ TypeError:無法讀取未定義的屬性'counter'”
問題:如何正確操作父變量?
在子組件中添加輸入字段:
@Input() counter: any;
然后,您可以在父html中綁定到此屬性:
<child-component-selector [counter]="counter"></child-component-selector>
您這樣做的方式錯誤,您無法做到這一點。.您必須通過@Input
標記以以下方式執行此@Input
例如:
export class AppComponent {
counter = '1/3';
}
在應用程序組件的html中
<ChildComponent [counter]="counter"></ChildComponent>
在你的孩子部分
import { Component, Input } from '@angular/core';
export class ChildComponent{
@Input() counter:any;
//after this you can use counter
}
在這里更多
您可以通過輸入屬性將父變量傳遞給子組件。
import {Input} from '@angular/core';
export class Page1Component {
@Input() counter;
SomeEvent($event) {
this.counter='2/3';
}
}
在您的應用中,您可以通過櫃台
app.component.html
<page1 [counter]="counter"><page1>
如果您還想更改父級的計數器,則可以定義輸出事件發射器,並在發生某些事件時在父級中調用方法
如果要更改父項的權限,請更新 :
import {Output} from '@angular/core';
export class Page1Component {
@Output() change: EventEmitter<any> = new EventEmitter();
SomeEvent($event) {
this.change.emit();
}
}
app.component.html
<page1 [change]="counterChanged()"><page1>
app.component.ts
export class AppComponent{
counterChanged() {
this.counter = "whatever value";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.