Home > front end >  How to get access to child component?
How to get access to child component?

Time:07-14

I have a component that accepts a config object and redners form inside:

 <dynamic-form (submitted)="formSubmitted($event)" [config]="config">
          <div >
            <button pButton type="button" (click)="add()">Добавить</button>
            <button pButton type="button" (click)="cancel()">Отмена</button>
          </div>
        </dynamic-form>

This component has form:

  public form: FormGroup;

How to get access to this form outside from parent component and submit form (or any actions with form)?

I can place button inside and emit Output. But I need to do that more flexibale to change buttons

Maybe it is wrong archirecture?

CodePudding user response:

Another way I could think of is @ViewChild, Using @ViewChild get access to the child component, and access form or any property of the component(example below).

@ViewChild(DynamicFormComponent) dynamicFormComponent: DynamicFormComponent;

someAction() {
  console.log(this.dynamicFormComponent.form);
}

Use @ViewChildren if you have multiple child components(Example Below)

@ViewChildren(DynamicFormComponent) dynamicFormComponents: QueryList<DynamicFormComponent>;
  • Related