Search code examples
angulartypescriptangular-components

In Angular How do I populate a property from the html


I have created a component called Wizard which has two properties: Sections & Steps

here is an extract from the component

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() {

  }
}

How can I populate the properties from the HTML view so that the following will populate the Section and Steps Properties?

<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>

Solution

  • You can do this inside your 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);
      }