繁体   English   中英

如何将属性从一个组件绑定到角度为4的App.Component?

[英]How to Bind Property from one component to App.Component in angular 4?

test.component.html

<input type="text" name="fname" [(ngModel)]="user">
<button
class="btn btn-primary">Update Server</button>

test.component.ts

import { Component, OnInit } from '@angular/core';
import { Input } from '@angular/core';

@Component({
  selector: 'app-testcomp',
  styleUrls: ['./testcomp.component.css']
})
export class TestcompComponent implements OnInit {

  constructor() { }
  @Input() user:any;
  ngOnInit() {

  }


}

在app.component.html中

<app-testcomp [user]="ide"></app-testcomp>
<button
(click)="onserclicked()">Clicked</button>

在其ts文件中

   import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent  {
  ide:any;

  onserclicked()
  {
    alert(this.ide)
  }
}

单击app.component.html ...中的按钮时,它显示的是undefined而不是在用户组件的文本框中输入的值

评论是正确的,但是您可以使用其他东西来实现它。 删除实际上不需要的输入,仅保留

user:any;

命名您的组件像

<app-testcomp #testcomp></app-testcomp>
<button (click)="onserclicked(testcomp.user)">Clicked</button>

然后一切都会起作用。

您需要使用装饰器@Output

app.component.html:

<app-testcomp [user]="ide" (userClick)="onserclicked($event)"></app-testcomp>
<button
(click)="onserclicked()">Clicked</button>

test.component.html

<input type="text" name="fname" [(ngModel)]="user">
<button
class="btn btn-primary" (click)="onChange()">Update Server</button>

test.component.ts

import { Component, OnInit } from '@angular/core';
import { Input } from '@angular/core';

@Component({
  selector: 'app-testcomp',
  styleUrls: ['./testcomp.component.css']
})
export class TestcompComponent implements OnInit {

  constructor() { }
  @Input() user:any;

  @Output()
  userClick: EventEmitter<any> = new EventEmitter<any>();

  public onChange(){
      this.change.emit();
  }

  ngOnInit() {

  }


}

你可以试试看。 我猜它正在工作。

您可以通过Todd Motto的本教程来了解所有组件事件

暂无
暂无

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

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