0

I'm trying to create an editable form component. I've looked at several answers on how to access parent data, but none of them answer the question which will fit these needs:

  1. There can be multiple form component's on the same page, (this means I cannot use a global service to control this)
  2. I do not know what form components will be added ahead of time. (this means that I will not be able to include them in the parent template)

Lets say I have an interface:

export interface EditOptions
{
    isEditing: boolean;
}

Now lets say I have a component with a button which controls the editing status like so:

import { Component } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser'
import { EditOptions } from '../../../models/editOptions';

@Component({
  selector: 'editable-form',
  templateUrl: '<div><button (click)="toggleEdit()">Edit</button></div>'
})
export class EditableFormComponent {
    editOptions: EditOptions = { isEditing: false };
    isEditing: boolean = false;

    toggleEdit() {
        this.editOptions.isEditing = !this.editOptions.isEditing;
    }

    getEditOptions() {
        return this.editOptions;
    }
}

Now Lets say I have a Child Component:

<div>
  <div [hidden]="!editOptions.isEditing">
    <input #inlineEditControl [required]="required" [name]="value" [(ngModel)]="value" [type]="type" [placeholder]="label" />
  </div>
  <div [hidden]="editOptions.isEditing">
    <label class="block bold">{{label}}</label>
    <div class="inline-edit">{{value}}&nbsp;</div>
  </div>
</div>

and the typescript file, (For simplicity issue's i've ommited the full code):

@Component({
  selector: 'inline-edit',
  templateUrl: 'inline-edit.html'
})
export class InlineEditComponent{
     @Input() editOptions: EditOptions;
     @Input() label: string;
     @Input() value: string;
}

Now I Can Construct a page like so:

<div>
    <editable-form #profileForm></editable-form>
    <inline-edit [(ngModel)]='user.username' [editOptions]='#profileForm.getEditOptions()'></inline-edit>
</div>

This works but I would like it to work so the parent controls everything is there a way I can do this instead:

<div>
    <editable-form #profileForm><inline-edit [(ngModel)]='user.username'></inline-edit></editable-form>
</div>

and then have the editable form component some how grab out all of the view children and set the editOptions from a list instead?

Matthew Green
  • 10,161
  • 4
  • 36
  • 54
johnny 5
  • 19,893
  • 50
  • 121
  • 195
  • I think this is what you want: [subscriptions](http://stackoverflow.com/questions/42423403/angular-2-notify-a-route-component-of-an-event-in-the-app-component) – trees_are_great Apr 24 '17 at 16:30
  • @Sam yeah kinda but in this case there would be no global service, each component is dependent on its parent. – johnny 5 Apr 24 '17 at 19:44

0 Answers0