在 Angular 如何从 html 填充 属性

In Angular How do I populate a property from the html

我创建了一个名为 Wizard 的组件,它有两个属性:Sections 和 Steps

这里是组件的摘录

import { Component, Input, OnInit } from '@angular/core';
import { Section } from './models/section';
import { Step } from './models/step';

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

  @Input() sections: Section[];
  @Input() steps: Step[];

  currentStep: Step;
  constructor() {

  }
}

如何填充 HTML 视图中的属性,以便以下内容填充部分和步骤属性?

<sym-wizard>
  <sections>
    <section name="name1"></section>
    <section name="name2"></section>
    <section name="name3"></section>
  </sections>

  <steps>
    <step name="step1" section="name1">
    </step>
    <step name="step2" section="name1"></step>
    <step name="step3" section="name2"></step>
    </steps>
</sym-wizard>

您可以在 WizardComponent:

中执行此操作

Stackblitz demo

  @ContentChildren(StepComponent, { descendants: true }) 
  _steps: QueryList<StepComponent>;

  @ContentChildren(SectionComponent, { descendants: true })
  _sections: QueryList<StepComponent>;

  ngAfterViewInit() {
    console.log(this._steps.toArray().length);
    console.log(this._sections.toArray().length);
  }

您可以查看 @ContentChilren 装饰器。 Angular docs。如果我对您的理解正确,这就是您所需要的。 所以,在你的情况下它会是这样的:

@ContentChildren("section") sectionsQuery!: QueryList<SectionComponent>;

然后在AfterViewInit挂钩:

ngAfterViewInit() {
    this.sections = this.sectionsQuery?.map(section => ({name: section.name}));
}

希望对您有所帮助。

我想这就是您要找的: Stackblitz
我在这个例子中使用了 div,但应该也适用于其他一切。