如何将childComponent的变量(或属性,例如[(ngModel)] =“ ush”)传递/使用到parentComponent中?

时间:2018-12-15 08:24:49

标签: angular variables properties

和我的父组件.ts是:

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

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

  // @ViewChild('test') appgreetcomponentreetComponent;

  ngAfterViewInit(): void {
  }    
  constructor() {
  }    
}

和我想在其中使用ush(or us = ush)的父HTML

<app-greet-component> 
<h1 class="head">Hello {{ us }}</h1><br>
<br><button type="button" btnp>Click here {{ us }}</button>
</app-greet-component>

和我的子组件.ts,我将'ush'变量放在名为'us'的公共变量中(但未定义),并将在我的父html中使用它:

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

@Component({
  selector: 'app-greet-component',
  templateUrl: './greet-component.component.html',
  styleUrls: ['./greet-component.component.css']
})

export class GreetComponentComponent implements OnInit {
  ush:any;
  public us = this.ush; 

  clic(){
    console.log(this.us);    
  }

  greet = 'Welcom to our restaurant! We are best in service.';  

  constructor() { } 

  ngOnInit() {
  }
}

和我由ngModel带到这里的孩子Html,想要在上面的我的父html中使用它:

    <div>
      your name: 
      <input type="text" #userName [(ngModel)]="ush">
      <ng-content select=".head"></ng-content>
      {{ greet }}<br> 
      <ng-content select="[btnp]"></ng-content>
      <br><br><br>
      <button type="button" (click)="clic()">click</button>
    </div>

请帮助我做到这一点,这意味着我应该添加或删除什么?

1 个答案:

答案 0 :(得分:0)

真的很感谢您的回答! 请不要再回答我的问题了! 我担心要补偿您的出色答案:)