0

i've got an input field and i want so set default values. But with ngModel the input fields are just empty. How do i set default values which the user can change?

<div class="control">
 <input #name="ngModel" [(ngModel)]="message.name" name="name" class="input" type="text" value="{{data.name}}" required>
 <p class="help is-danger" *ngIf="name.touched && name.invalid">This field is required</p>
</div>
 <button (click)="saveEdit()" [disabled]="!(name.valid)">Save</button>

i'm not very experienced in angular/webdev...

Thank you!

Solution:

Add

  ngAfterViewInit() {
    this.message.name = this.data.name
}

to ts.component

3
  • 1
    In ngAfterViewInit() you can set the message.name value and it will be bind in the html input field. Commented Jan 23, 2021 at 22:03
  • 1
    @Marco that worked perfectly. ty! Commented Jan 23, 2021 at 22:09
  • 1
    Can you accept the answer of @Shivansh Sethas it tells the same things as me ? Commented Jan 24, 2021 at 8:19

2 Answers 2

1

<input [(ngModel)]="message.name" name="name" class="input" type="text" required>

In your component :

message : any = { name: 'YOUR_DEFAULT_VALUE', }

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

1 Comment

that solution is working. Im gonna keep this one instead of using the ngAfterViewInit(). Thanks!
0

 <input  [(ngModel)]="message" name="name" class="input" type="text"required>

In your Typescript file Add message = 'defaultvalue'

1 Comment

this one is not working because message is an object. See @Shivansh Seth solution, which is almost the same. TY!

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.