[英]Angular6 Data from Input to other component
我有一个组件,其中写道:Hello Angular6
app.component.html:
<hello name="{{ name }}"></hello>
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular 6';
}
任务是制作一个新组件,称为"Userchange"
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-user-change',
templateUrl: './userchange.component.html',
styleUrls: ['./userchange.component.css']
})
export class UserChangeComponent {
@Input() change: string;
}
那里有一个按钮和一个文本类型输入,它应该像这样工作:在输入框中写一些东西,然后按下按钮,app.component中的'name'
应该是给定的文本。
你能帮我吗?
我刚刚开始学习Angular。
欢迎来到Angular! 有几种方法可以做到这一点。 这是一个
要查看它们如何组合在一起,可以在此处的 StackBlitz中查看此代码。
在userChange.component.html中:
<input type="text" #myTextInput value="DefaultValue"/>
<button (click)="changeName(myTextInput.value)">Click me to change the name</button>
在userChange.component.ts中:
nameValue: string;
@Output() nameChange = new EventEmitter();
changeName(val){
this.name = val;
}
@Input()
get name() {
return this.nameValue;
}
set name(val) {
this.nameValue = val;
this.nameChange.emit(this.nameValue);
}
App.Component.html将使用双向数据绑定,这意味着您的变量(在本例中为名称)将通过eventEmitter用作变量输入和输出,以向父级发信号通知名称已更改,并且采取相应行动:
<userChange [(name)]="name"></userChange>
Hi {{name}}
我也在学习有角的:)。 这是另一个版本 ,可能没有以前的答案那么简洁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.