Angular2 - 单击以编辑表单域

时间:2016-05-27 07:15:44

标签: angular

我有一个从服务中提取数据并按如下方式显示的表单

@Component({
    selector: 'profile',
    template: `<h1>Profile Page</h1>
    <form [ngFormModel]="myForm" (ngSubmit)="onSubmit()" #f="ngForm">
    <div *ngFor="#prof of profileObject">
        <label from="name">Name</label>
        <input [ngFormControl]="myForm.controls['name'] "type="text" id="name" #name="ngForm" [(ngModel)]="prof.userFirstName">
    </div>
    <button name="submit" type="submit">submit</button>
    </form>

    <a [routerLink]="['../Dashboard']">Back to Dash</a>
    `,
    directives: [ROUTER_DIRECTIVES]
})

export class ProfileComponent implements OnInit {
    myForm: ControlGroup;
    userEmail = JSON.parse(localStorage.getItem('profile'));
    public profileObject: Object[];


    constructor(private fb: FormBuilder, private apartmentService: ApartmentService) {
        this.apartmentService = apartmentService;
    }


    onSubmit(form) {
        console.log(this.myForm);
        //post to rest API
    };

    ngOnInit(): any {
        this.apartmentService.getProfile(this.userEmail.email).subscribe(res => this.profileObject = res);
        this.myForm = this.fb.group({
            'name': ['', Validators.required],
        });
    }
}

当组件加载模板时,显示预先填充在输入文本中的数据。

如何在标签中显示数据,并在用户点击时将其更改为输入文字?基本上想要在表单中实现点击编辑功能

1 个答案:

答案 0 :(得分:10)

您可以使用*ngIf在两个视图之间切换:

    <label *ngIf="!isEdit" (click)="isEdit=true" from="name">Name</label>
    <input *ngIf="isEdit" (keydown.enter)="isEdit=false" 
        [ngFormControl]="myForm.controls['name'] "type="text" 
        id="name" #name="ngForm" [(ngModel)]="prof.userFirstName">