首页 > 解决方案 > 如何在 Angular 中创建一个公共子组件

问题描述

我是 Angular 的新手。我将为所有 ui 组件开发通用下拉栏。因此,我将与其他父组件创建一个通用的子可重用组件。如何创建一个通用的子组件。?

这是我的父组件文件夹结构。

在此处输入图像描述

标签: angularparent-childangular-components

解决方案


父组件不能使用数据绑定来读取子属性或调用子方法。您可以通过为子元素创建模板引用变量,然后在父模板中引用该变量来完成这两项操作,如下例所示。

下面是一个子 CountdownTimerComponent,它反复倒计时到零并发射火箭。它具有控制时钟的启动和停止方法,并在自己的模板中显示倒计时状态消息。

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

@Component({
  selector: 'app-countdown-timer',
  template: '<p>{{message}}</p>'
})
export class CountdownTimerComponent  implements OnInit, OnDestroy {

  intervalId = 0;
  message = '';
  seconds = 11;

  clearTimer() { clearInterval(this.intervalId); }

  ngOnInit()    { this.start(); }
  ngOnDestroy() { this.clearTimer(); }

  start() { this.countDown(); }
  stop()  {
    this.clearTimer();
    this.message = `Holding at T-${this.seconds} seconds`;
  }

  private countDown() {
    this.clearTimer();
    this.intervalId = window.setInterval(() => {
      this.seconds -= 1;
      if (this.seconds === 0) {
        this.message = 'Blast off!';
      } else {
        if (this.seconds < 0) { this.seconds = 10; } // reset
        this.message = `T-${this.seconds} seconds and counting`;
      }
    }, 1000);
  }
}

承载定时器组件的 CountdownLocalVarParentComponent 如下:

import { Component } from '@angular/core';
import { CountdownTimerComponent } from './countdown-timer.component';

@Component({
  selector: 'app-countdown-parent-lv',
  template: `
  <h3>Countdown to Liftoff (via local variable)</h3>
  <button (click)="timer.start()">Start</button>
  <button (click)="timer.stop()">Stop</button>
  <div class="seconds">{{timer.seconds}}</div>
  <app-countdown-timer #timer></app-countdown-timer>
  `,
  styleUrls: ['../assets/demo.css']
})
export class CountdownLocalVarParentComponent { }

父组件不能数据绑定到子组件的 start 和 stop 方法,也不能绑定到它的 seconds 属性。

您可以在代表子组件的标记上放置一个局部变量#timer。这为您提供了对子组件的引用以及从父模板中访问其任何属性或方法的能力。

我希望这个例子对你有帮助


推荐阅读