Angular 显示所选组件的标题

Angular display title of selected component

我的问题很简单

router-outlet 中显示我的页面,例如 /contact/home/meetus

(如何)我可以在{{title}}中显示活动组件的名称?

这甚至可能吗,还是我必须在每个组件内移动我的标题栏?

您可以:

  1. 创建一个新组件,将其命名为 header,并将其放置在您的页面中。该组件将负责显示标题/任何你喜欢的header

  2. 使用服务并在有人输入特定组件时更新 title 变量

你可以用 ComponentFactoryResolver

constructor(private resolver: ComponentFactoryResolver) {}

onActivated(component) {
  this.activeSelector =    
  this.resolver.resolveComponentFactory(component.constructor).selector;    
}

在模板上,

<router-outlet (activate)="onActivated($event)"></router-outlet>

STACKBLITZ DEMO

您可以使用 Angular titleService 在 header 组件中显示页面标题,如下所示:

Header 组件.ts:

export class AppComponent {
  public constructor(private titleService: Title ) { }
}

Header 分量 .html:

<div class="title-bar">
    {{titleService.getTitle()}}
</div>

然后在任何组件中,您可以使用 Angular titleService 设置页面标题,它会自动更改标题和 header 部分:

export class AppComponent implements OnInit { {
  public constructor(private titleService: Title ) { }

  ngOnInit() {
    this.titleService.setTitle("Component's title");
  }
}

您可以创建一个 AppService 来保存应用程序 title 并将其作为可观察对象提供(使用 getset 等访问器方法)。

@Injectable()
export class AppService {
  private title = new BehaviorSubject<String>('App title');
  private title$ = this.title.asObservable();

  constructor() {}

  setTitle(title: String) {
    this.title.next(title);
  }

  getTitle(): Observable<String> {
    return this.title$;
  }
}

然后在将保存(并显示)title 的组件(比如 AppComponent)中,您订阅 appService#getTitle() 方法并更新 title 属性相应地。

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title: String;

  constructor(private appService: AppService) { }

  ngOnInit() {
    this.appService.getTitle().subscribe(appTitle => this.title = appTitle);
  }
}

现在在每个 component 中注入 AppService(需要更新标题时)并调用 appService#setTitle()。例如,一个 hello 组件:

@Component({
  selector: 'hello',
  template: `<p><b>Hello</b> component content</p>`,
  styles: []
})
export class HelloComponent  {
  
  constructor(private appService: AppService) { }

  ngOnInit() {
    this.appService.setTitle('Hello Component');
  }
}

看到这个 Working Demo(用 Angular 6 测试)