To be very short i am using this Plunker I have a scenario where i have to create controls dynamically by reading the elements data from a service. So when i read the data from
Looking at this example Angular.io - Dynamic Forms, it essentially builds a form from metadata at runtime.
There's a couple of comments indicating that the example isn't quite finished.
@Injectable()
export class QuestionService {
// Todo: get from a remote source of question metadata
// Todo: make asynchronous
getQuestions() {
...
These are the steps I took to finish it off and clean out the error messages.
Changed getQuestions
to asynchronously return questions.
Injectable()
export class QuestionService {
constructor(
private http: Http
) {}
getQuestions$() {
const url = 'https://api.myjson.com/bins/d0srd';
return this.http.get(url)
.map(response => response.json())
.map(questionMetadata => this.metadataToQuestions(questionMetadata))
.map(questions => questions.sort((a, b) => a.order - b.order))
}
private metadataToQuestions(questionMetadata) {
return questionMetadata.questions.map(this.toQuestion)
}
private toQuestion(elementData) {
// expand for additional control types
return new TextboxQuestion({
key: elementData.elementname,
label: elementData.displaytext,
value: elementData.elementvalue,
required: false,
order: elementData.sortorder
})
}
}
Changed variable questions
type to observable, added async pipe to template.
@Component({
...
template: `
Job Application for Heroes
`,
...
})
export class AppComponent implements OnInit {
questions$: Observable;
constructor(
private questionService: QuestionService
) {}
ngOnInit() {
this.questions$ = this.questionService.getQuestions$();
}
}
Changed @Input variable questions
to be set/get style, to handle initial null value.
Changed hook where form is created from ngOnInit
to ngOnChanges
to handle async arrival of questions.
export class DynamicFormComponent implements OnChanges {
private _questions = [];
@Input()
set questions(value: any[]) {
this._questions = value || [];
}
get questions(): any[] {
return this._questions;
}
...
ngOnChanges() {
this.form = this.qcs.toFormGroup(this.questions);
}
}
Add additional check to isValid
getter to ensure the control being validated exists.
export class DynamicFormQuestionComponent {
...
get isValid() { return this.form.controls[this.question.key]
? this.form.controls[this.question.key].valid : true; }
}