【问题标题】:In Angular How do I populate a property from the html在 Angular 中,我如何从 html 中填充属性
【发布时间】:2020-08-20 01:17:10
【问题描述】:

我创建了一个名为 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>

【问题讨论】:

    标签: angular typescript angular-components


    【解决方案1】:

    你可以在你的 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);
      }
    

    【讨论】:

    • 嗨,我已将示例编辑为没有 [sections]="sections" [steps]="steps"
    • 我已经更新了我的答案。我将整理一个 stackblitz 演示......如果我还没有做好它会更容易理解。
    • 谢谢@julianobrasil 我还没有在我的例子中得到这个工作,但看看你的 Stackbliz 这似乎是我需要做的
    【解决方案2】:

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

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

    然后在AfterViewInit钩子里:

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

    希望对您有所帮助。

    【讨论】:

      【解决方案3】:

      我认为这就是您要寻找的: Stackblitz
      我在此示例中使用了 div,但也应该适用于其他所有内容。

      【讨论】:

        猜你喜欢
        • 2019-03-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-01
        相关资源
        最近更新 更多