Home > Mobile >  My input inside a form in Angular is not showing it's default value
My input inside a form in Angular is not showing it's default value

Time:06-05

I have a form in which I would like to have a default value inside one of the input, that default value being the user's display name, however, it's not showing, and even "hi" is not shown when added as the default value of the input, I'm not sure what it is I should do :

<form [formGroup]= "postForm" (ngSubmit)="onSubmit()" novalidate>
  <div >
    <label>Title</label>
    <input type="text" formControlName="title"  required>
  </div>

  <div >
    <label>Content</label>
    <input type="text" formControlName="message"  required>
  </div>

  <div  *ngIf="authService.userData as user" >
    <input type="text" value="{{user.displayName}}" formControlName="owner" >
  </div>

  <div >
    <button type="submit"  [disabled]="!postForm.valid">Create</button>
  </div>


</form>

And this is the typescript component related to it :

    import { Component, OnInit } from '@angular/core';
import {AuthService} from "../shared/services/auth.service";
import { PostService } from '../post.service';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from "@angular/router";



@Component({
  selector: 'app-create-post',
  templateUrl: './create-post.component.html',
  styleUrls: ['./create-post.component.scss']
})
export class CreatePostComponent implements OnInit {
  public postForm: FormGroup;

  constructor(public postService: PostService,
              public formBuilder: FormBuilder,
              public router: Router,public authService: AuthService){
    this.postForm = this.formBuilder.group({
      title: [''],
      message: [''],
      owner: [''] ,
      date: new Date().toLocaleString()
    })
  }

  ngOnInit(): void {
  }

  onSubmit() {
    this.postService.createPost(this.postForm.value);
    this.router.navigate(['list-posts']);
  };

}

Help is very needed and appreciated, I would also like to point out that I have tried to directly put the diplayname value in the TypeScript file but it doesnt exist there, its only available from the html file.

CodePudding user response:

You shouldn't use value with Angular controlled forms, instead, the initial value is the one you provide in the typescript file, so, please remove the value part from the html, and replace in the typescript file owner: [''] , with owner: this.authService.userData or even owner: 'hi' just to make sure it works.

  • Related