Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - form in Edit / View mode

I'm working on my first angular2 application, I need to implement a form that allows edit and view mode.

In view mode all the textbox items must di enabled , otherwise when I'm in view mode I want to show simple plain text ( like span element ).

What is the best practice to do that?

Is there some standard component or I have to implement some ngIf ?

Thanks

like image 254
DarioN1 Avatar asked Apr 13 '17 12:04

DarioN1


People also ask

Is edit mode in angular?

Angular Add/Edit Component The add/edit component is used for both adding and editing users in the angular app, the component is in "add mode" when there is no user id route parameter, otherwise it is in "edit mode".

What are the two types of forms in Angular?

Angular provides two different approaches to handling user input through forms: reactive and template-driven.

What is reactive and template driven forms in Angular?

Template Driven Forms are based only on template directives, while Reactive forms are defined programmatically at the level of the component class. Reactive Forms are a better default choice for new applications, as they are more powerful and easier to use.


2 Answers

You could use *ngIf to change between an View mode(contains regular interpolation) and Edit mode(contains the form). ie:

<form #myForm="ngForm">
    <div>
        <label>Var 1</label>
        <input *ngIf="editMode" type="text" name="var1" [(ngModel)]="var1" />
        <span *ngIf="!editMode">{{var1}}</span>
    </div>
</form>

This let's you style the form however you want, but comes at the cost of having a second line to display the value and tagging everying with *ngIf.

The other option, that has already been mentioned, is you can disable the controls on the form using:

<input type="text" name="var1" [(ngModel)]="var1" [disabled]="!editMode"/>
like image 103
Tyler Jennings Avatar answered Oct 22 '22 02:10

Tyler Jennings


You can do this by adding a condition to each input field, for example

<button type="submit" [disabled]="!myForm.form.valid">Enter</button>

this obviously needs to check the controller file for some expression like

[disabled]="!isEditable"

If this is true you can edit the field

like image 44
Ulug Toprak Avatar answered Oct 22 '22 01:10

Ulug Toprak