I want to create an update page that the user can update Recipe
values for. I know how to use two way data binding for creating new Recipe
, but how do I load a page that has the values taken from the database loaded into the input fields initially?
So i have a model Recipe
export class Recipe {
constructor(
public name: String
) {}
}
in a RecipeComponent
import { Recipe } from './Recipe';
export class RecipeComponent {
data = new Recipe('');
}
shown in an html form
<input type="text" class="form-control" id="name"
required
[(ngModel)]="data.name" />
<p>Hello {{ data.name }}!</p>
This works great if I want to create a new model from scratch. But I want the user to be able to see what the exiting values are, so somehow in the data = new Recipe('')
line i want that to use my RecipeService
to populate the inputs.
You need one service, and get data from service to component. and then bind it to [()] ng model.
service.ts
@Injectable()
export class DataService {
data = {
name: 'wesbos'
};
constructor() { }
getData(){
return of(this.data);
}
}
component.ts
export class AppComponent {
name = this.dataService.getData();
constructor(private dataService: DataService){}
}
component.html
<div *ngIf="name | async as dataName">
default Name : <input [(ngModel)]="dataName.name">
</div>