0

Below is the sample of template driven form in angular 6 which is dynamic and it could be any number of form. So I don't want to create and use variable in class something like [(ngModel)]="anyVariable". If I write value="Rakesh" in the form then it is not showing.

So, How can I set default value of firstName and lastName input?

<form #paxForm="ngForm" name="passengerForm" novalidate>

    <label>First name*</label>
    <input type="text" value="Rakesh" name="firstName" ngModel/>

    <label>Last name*</label>
    <input type="text" value="" name="lastName" ngModel required/>

    <label>Mobile number*</label>
    <input type="tel" name="mobileNumber" value="" ngModel required/>

    <input type="button" value="Submit" (click)="submitPaxForm(paxForm)"/>
</form>

Return Value:

paxForm:{
    value:{
        mobileNumber: "97987987",
        firstName: "rakesh",
        lastName: "pal"
    }
}
1
  • can you make a stackblitz with your example ? Commented Nov 28, 2018 at 10:19

3 Answers 3

1

Simple as that:

<input type="text" name="firstName" ngModel="Rakesh"/>

https://stackblitz.com/edit/so-53517039

Sign up to request clarification or add additional context in comments.

Comments

1

I did something like this by relay on two way data binding so it's easy for me to get all forms values

consider this example

AppComponent

  formsValues=[
    {
        mobileNumber: "97987987",
        firstName: "rakesh",
        lastName: "pal"
    } , 
    {
        mobileNumber: "2233556",
        firstName: "sam",
        lastName: "well"
    }
  ]

Template

<div *ngFor="let frm of  formsValues" class="form">
    <label>First name*</label>
    <input type="text" value="Rakesh" name="firstName" [(ngModel)]="frm.firstName"/>

    <label>Last name*</label>
    <input type="text" value="" name="lastName" [(ngModel)]="frm.lastName" required/>

    <label>Mobile number*</label>
    <input type="tel" name="mobileNumber" value="" [(ngModel)]="frm.mobileNumber" required/>
    <input type="button" value="Submit" (click)="submitPaxForm(frm)"/>
</div>

demo stackblitz

but I think reactive form array is much better for your case

Comments

0

I had a similar issue. Got it fixed by directly aasigning the default value to ngModel.

Example:

'<form  #userData="ngForm" (ngSubmit)="getData(userData.value)">
     <div class="fields">
     <label>Building</label><input class="form-control" type="text" id='building' 
     name='building' ngModel='1234'>
     <label>Floor</label><input class="form-control" type='text' id='floor' 
     name='floor' ngModel='2'>
     </div>
     <button type="submit">Submit</button>
     </form>'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.