如何在Angular中创建公共子组件

问题描述

我是angular的新手。我将为所有ui组件开发通用的下拉栏。因此,我将与其他父组件一起创建一个通用的子可重用组件。 / p>

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

enter image description here

解决方法

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

以下是一个子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。这样可以为子组件提供参考,并可以从父模板中访问其任何属性或方法。

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