首页 > 解决方案 > 如何更新其他组件的html文本值

问题描述

这是我的 app.component.html 源代码:

 <split-flap></split-flap>
 <button (click)="flip('+')">+</button><button (click)="flip('-')">-</button>

这是我的 app.component.ts 源代码:

import { Component } from '@angular/core';
import { SplitFlapComponent } from './split-flap/split-flap.component';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers:[SplitFlapComponent]
})
export class AppComponent {
  constructor(private splitFlapComponent: SplitFlapComponent)
  {

  }
  flip(flag)
  {
    console.log(flag);
    this.splitFlapComponent.title=flag;
  }
}

这是我的 split-flap.component.ts:

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

@Component({
  selector: 'split-flap',
  templateUrl: './split-flap.component.html',
  styleUrls: ['./split-flap.component.css']
})
export class SplitFlapComponent implements OnInit {

  title: string;
  constructor() {
    this.title = 'split-flap works1!';
  }
  ngOnInit() {
  }

}

这是我的 split-flap.component.html:

<p>{{title}}</p>

我的 app.component.html 有两个按钮,它们都传递一个符号到split-flap.component,你能告诉我如何更新 split-flap.component.html 内容吗?因为大多数示例仅适用于输入框,所以我找不到<p>.

标签: javascriptangular

解决方案


试试这样:

解决方案 1:@Input()

app.component.html

<split-flap [title]="title"></split-flap>

app.component.ts

title: string;

constructor() {
  this.title = 'split-flap works1!';
}

flip(flag)
{
  console.log(flag);
  this.title=flag;
}

split-flap.component.ts:

@Input() title: string

解决方案 2:ViewChild()

app.component.html

<split-flap  #child ></split-flap>

app.component.ts

@ViewChild('child') child: SplitFlapComponent ;

flip(flag)
{
  console.log(flag);
  this.child.title=flag;
}

推荐阅读