Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Component } from '@angular/core';
- import { FormGroup, Validators, FormControl } from '@angular/forms';
- interface Person{
- id: number,
- name: string,
- value: string,
- editMode: boolean
- }
- @Component({
- selector: 'app-root',
- template: `
- <form [formGroup]="form">
- <table style="border: 1px solid black">
- <thead>
- <tr>
- <td>Name</td>
- <td>Value</td>
- <td></td>
- </tr>
- </thead>
- <tbody>
- <tr *ngFor="let object of obj">
- <td>
- <label *ngIf="!object.editMode">{{ object.name }} </label>
- <input *ngIf="object.editMode" type="text" [name]="getName(object.id)" [id]="getName(object.id)" [value]="object.name" [formControlName]="getName(object.id)"/>
- <p *ngIf="getValidateName(object.id).invalid">
- Invalid Name
- </p>
- </td>
- <td>
- <label *ngIf="!object.editMode">{{ object.value }}</label>
- <input *ngIf="object.editMode" type="text" [name]="getValue(object.id)" [id]="getValue(object.id)" [value]="object.value" [formControlName]="getValue(object.id)" />
- <p *ngIf="getValidateValue(object.id).invalid">
- Invalid Value
- </p>
- </td>
- <td><input type="button" value="edit" (click)="onEdit(object)" [disabled]="getValidateName(object.id).invalid || getValidateValue(object.id).invalid"></td>
- </tr>
- </tbody>
- </table>
- </form>
- <p>Form Value: {{ form.value | json }}</p>
- `
- })
- export class AppComponent {
- form: FormGroup;
- obj: Array<Person> = [
- {id:2,name: 'John', value: 'John value',editMode : false},
- {id:3,name: 'Sara', value: 'Sara value',editMode : false},
- {id:4,name: 'Moss', value: 'Moss value',editMode : false}
- ];
- private readonly NAME_PREFIX = 'name-';
- private readonly VAL_PREFIX = 'value-'
- public formInit(){
- this.form = new FormGroup({});
- this.obj.forEach(x => {
- const controlId = x.id;
- const nameValidator = [Validators.required];
- const valValidator = [Validators.required,Validators.minLength(5)];
- this.form.addControl(this.NAME_PREFIX+controlId, new FormControl(x.name, nameValidator));
- this.form.addControl(this.VAL_PREFIX+controlId, new FormControl(x.value, valValidator));
- });
- }
- ngOnInit() {
- this.formInit();
- }
- getName(id: string): string {
- return this.NAME_PREFIX+id;
- }
- getValue(id: string): string {
- return this.VAL_PREFIX+id;
- }
- getValidateName(id: string): FormControl{
- return this.form.get(this.NAME_PREFIX+id) as FormControl;
- }
- getValidateValue(id: string): FormControl{
- return this.form.get(this.VAL_PREFIX+id) as FormControl;
- }
- public onEdit(p: Person){
- const target = this.obj.find(x => x.name == p.name);
- target.editMode = !target.editMode;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement