首页 > 解决方案 > 如何将父标题更改为Angular中子标题的值?

问题描述

我正在寻找可以在父组件中动态切换(取决于我们所在的组件)值的解决方案。每个组件的值应该不同。

这种解决方案的服务是不是太多了?Angular 中是否有更简单的解决方案?

父级 - 一些文本 {{ title }}

Child1 - 标题 = “标题一” Child2 - 标题 = “标题二”

等等

标签: angularparent

解决方案


尝试使用EventEmitter

子组件.ts

import { Output, EventEmitter } from '@angular/core'; 
title: string;
@Output() titleChange: EventEmitter<any> = new EventEmitter();

ngOnInit() {
  this.title = 'child title';
  this.titleChange.emit(this.title);
}

父组件.html

<p>{{title}}</p>
<app-child (titleChange)="onTitleChange($event)"></app-child>

父组件.ts

title: string

onTitleChange(value: string) {
   this.title = value;
}

推荐阅读