简体   繁体   中英

Angular6 Data from Input to other component

I have a component, which writes: 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';
}

Task is, to make a new component, called "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;  
}

There I have a button and a text type input, it should work like that: I write something to the input box, then I press the button, and the 'name' in the app.component should be the given text.
can you please help me with that?

I just begun learning Angular.

Welcome to Angular! There are a few ways to do this. Here's one.

To see how it all fits together, you can view this code in StackBlitz here.

In userChange.component.html:

<input type="text" #myTextInput value="DefaultValue"/>
<button (click)="changeName(myTextInput.value)">Click me to change the name</button>

In 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 will use two-way data binding, which means that your variable (in this case name) will be used as both a variable input and an output via the eventEmitter to signal back to the parent that name has changed, and to act accordingly:

<userChange [(name)]="name"></userChange>
Hi {{name}}

For further reference I'd reccomend going through Angular's tour of heroes and thoughtram's excellent post on Two-way Data Binding.

I'm also learning angular :). Here is another version , probably less neat then the previous answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM