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:
- There can be multiple form component's on the same page, (this means I cannot use a global service to control this)
- 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}} </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?