简体   繁体   English

使用@output将角度从子组件发送到父组件

[英]angular using @output to sent data from child to parent component

I have some data that I am passing from my child to parent component and I want it to check if its empty or it has some value inside automatically. 我有一些要从孩子传递给父组件的数据,我希望它检查它是否为空或是否自动具有某些值。

this is in my login.compunent.ts - child ts 这是在我的login.compunent.ts中-儿童ts

@Output() update=new EventEmitter<string>();
userEmail = "a@b.com";
authUser(loginForm) {      
      this.update.emit(userEmail);
      this.router.navigate(['/home']);
  }

this is in my app.compunent.ts - parent ts 这是在我的app.compunent.ts-父ts中

  emailData:string;

  onUpdate(userEmail:string){
    console.log("userEmail")
    if(userEmail !== ''){
      this.emailData = userEmail
      console.log(userEmail)
    }
  }

this is in my app.compunent.html - parernt html 这是在我的app.compunent.html-上一篇html

{{emailData}}
<router-outlet (update)="onUpdate($event)"></router-outlet>

I'm not sure I understand you completely but if you want to pass data from your child to your parent "automatically" I believe you have to implement a two-way bindable property. 我不确定我是否完全理解您,但是如果您想将数据从孩子“自动”传递给父母,我相信您必须实现双向可绑定属性。

You do that like this 你是这样子的

child.ts 孩子

export class SomeComponent  {
  ...
     @Input() something;
     // it's important to name it with the 'Change' suffix 
     @Output() somethingChange = new EventEmitter();
  ...

parent.html parent.html

<some-component [(something)] = "someFieldYouWantToTwoWayBindTo"></some-component>

now whenever you update something from your child the field someFieldYouWantToTwoWayBindTo will also be updated 现在,每当您从孩子那里更新somethingsomeFieldYouWantToTwoWayBindTo字段也将被更新

Now if you want to check what's in something and only filter certain cases then implement a setter for someFieldYouWantToTwoWayBindTo 现在,如果你要检查什么的something ,只过滤某些情况下,然后实施二传手someFieldYouWantToTwoWayBindTo

parent.ts 父母

_someFieldYouWantToTwoWayBindTo
set someFieldYouWantToTwoWayBindTo(value) {
    if(value !== '')
      this._someFieldYouWantToTwoWayBindTo = value;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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