【问题标题】:Angular6 Data from Input to other component从输入到其他组件的Angular6数据
【发布时间】:2018-12-04 04:00:08
【问题描述】:

我有一个组件,上面写着: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 6,那么它应该被标记为 angular 而不是 angularjs。 AngularJS 是 pre2 库,与现代 Angular 大不相同。还应该更新标题以反映 Angular 6 vs AngularJS
  • @scrappedcola 谢谢,完成了
  • 你看过angular 6英雄之旅教程吗?
  • 我建议查看 firegloves 和 stackoverflow.com/questions/39325503/… 提到的教程,注意 angular 2+ 的工作原理基本相同,只有当您尝试返回 pre2 时,它才被视为不同的库。跨度>
  • @firegloves 我有,我就是不明白。

标签: html angular angular6


【解决方案1】:

我也在学习 Angular :)。这是another version,可能不如上一个答案那么整洁。

【讨论】:

【解决方案2】:

欢迎使用 Angular! 有几种方法可以做到这一点。这是一个。

要了解它们是如何组合在一起的,您可以在 StackBlitz here. 中查看此代码

在 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}}

为了进一步参考,我建议阅读 Angular 的英雄之旅和 thinkram 在Two-way Data Binding. 上的精彩帖子

【讨论】:

    猜你喜欢
    • 2020-11-06
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 2018-03-14
    • 2019-06-11
    • 1970-01-01
    • 2019-11-21
    • 2015-01-25
    相关资源
    最近更新 更多