我需要編輯功能幫助。當我點擊編輯按鈕時,我需要將這些項目加載到表單中。這就是我的應用程序的工作方式,首先,有一個用戶列表,然後您可以單擊該特定用戶的「查看更多」按鈕,它會將您重定向到一個新頁面。在新的頁面中,你會發現「編輯按鈕」所以我試圖通過選擇它與聯繫人編號做我的編輯功能,因爲我沒有索引,因爲它是一個對象。只有一個問題,那就是我如何加載編輯表格中的項目?我相信這是一個非常簡單的問題,但我對此感到困惑。如果您有更好的解決方案,請幫助我。將表單中的項加載到角度編輯
用戶detail.component.ts
export class UserDetailComponent implements OnInit {
user: User;
id: number;
constructor(private userService: UserService,
private route: ActivatedRoute,
private router: Router) { }
ngOnInit() {
this.route.params
.subscribe((params: Params) => {
this.id = +params['id'];
this.user = this.userService.getUser(this.id);
});
}
onEditDetail(index: number) {
this.router.navigate(['users', this.id, 'edit']);
}
}
用戶edit.component.html
<div class="card-block">
<form (ngSubmit)="onUpdateUser(f)" #f="ngForm">
<div class="form-group">
<label for="First Name">First Name</label>
<input type="text" class="form-control" [(ngModel)]="user.f_name" name="f_name" ngModel required>
</div>
<div class="form-group">
<label for="Last Name">Last Name</label>
<input type="text" class="form-control" [(ngModel)]="user.l_name" name="l_name" ngModel required>
</div>
<div class="form-group">
<label for="Contact Number">Contact Number</label>
<input type="number" class="form-control" [(ngModel)]="user.contact_no" name="contact_no" ngModel required pattern="^[1-9]+[0-9]*$">
</div>
<button class="btn btn-warning pull-right" [disabled]="!f.valid"><i class="fa fa-download" aria-hidden="true"></i> Update</button>
</form>
</div>
個用戶edit.component.ts
export class UserEditComponent implements OnInit {
@ViewChild('f') editForm: NgForm;
user: User;
id: number;
constructor(private userService: UserService,
private route: ActivatedRoute,
private router: Router) { }
ngOnInit() {
this.route.params
.subscribe((params: Params) => {
this.id = +params['id'];
this.user = this.userService.getUser(this.id);
});
}
onUpdateUser(form: NgForm) {
const value = form.value;
const updatedUser = new User(value.f_name, value.l_name, value.contact_no);
alert("Successfully Updated");
this.router.navigate(['users', this.id]);
}
}
user.service.ts
import { User } from './user.model';
import { Subject } from 'rxjs/Subject';
export class UserService {
usersChanged = new Subject<User[]>();
private users: User[]= [
new User('Harry', 'James', 99999889),
new User('Thomas', 'Baker', 99638798)
];
getUsers() {
return this.users.slice();
}
getUser(index: number) {
return this.users[index];
}
addUser(user: User){
this.users.push(user);
this.usersChanged.next(this.users.slice());
}
deleteUser(index: number){
this.users.splice(index, 1);
this.usersChanged.next(this.users.slice());
}
}
據我所知,'this.editForm.setValue'語法僅供反應形式。但是你似乎在使用模板驅動的表單。 – DeborahK
@DeborahK。那麼什麼是模板驅動的equiavalent? – Joseph
在下面使用ngModel綁定作爲@mok提及。 – DeborahK