javascript - 在 Angular 中点击按钮将响应式表单的值传递给另一个组件
我有两个组件(RegisterComponent 和 Subscription),第一个组件(RegisterComponent)包含一个具有三个值(firstname、lastname、email)的响应式表单和一个注册按钮。我想点击注册按钮后重定向到 Subscription,并显示用户的 firstname、lastname 和 email。registercomponent.html
<form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label class="float-left">firstName</label>
<input type="text" formControlName="firstName" class="form-control" />
</div>
<div class="form-group">
<label class="float-left">lastName</label>
<input type="text" formControlName="lastName" class="form-control" />
</div>
<div class="form-group">
<label class="float-left">email</label>
<input type="text" formControlName="email" class="form-control" />
</div>
</form>
registercomponent.ts
registerForm: FormGroup;
constructor(private formBuilder: FormBuilder,private router: Router) {
}
ngOnInit(): void {
this.registerForm = this.formBuilder.group({
firstName: [''],
lastName: [''],
email: ['']
});
onSubmit() {
this.router.navigate(['/Subscription']);
}
subscriptioncomponent.html
<div>
Here i want to display the firstname,lastname and email of user
</div>
app-routing.module.ts
{ path: "register", component: RegisterComponent },
{ path: "subscription", component:SubscriptionComponent}
当我点击按钮时,如何将表单的值传递给我的订阅组件并显示它。
答案#1
有不同的方法可以将数据从一个组件传递到另一个组件。
Angular 允许我们向路由传递数据。数据可以是静态的或动态的。
如果你只想传递3个值,那么请按照以下解决方案:-
registercomponent.ts
onSubmit() {
const firstname = this.registerForm.get('firstname').value;
const lastname = this.registerForm.get('lastname').value;
const email = this.registerForm.get('email').value;
this.router.navigate(['/Subscription' , firstname, lastname, email]);
}
app-routing.module.ts
{ path: "subscription/:firstname/:lastname/:email", component:SubscriptionComponent}
然后通过你的 subscriptioncomponent 中的 params 获取值。
subscriptioncomponent.ts
constructor(private route: ActivatedRoute){}
ngOnInit(){
this.route.params.subscribe(params=>{
this.firstname = params['firstname'];
this.lastname = params['lastname'];
this.email = params['email'];
})
}
答案#2
在 onSubmit 函数中像下面这样更改 navigate 函数的参数列表
onSubmit() {
this.router.navigate(['/Subscription', this.registerForm.value]);
}
// 像这样,this.router.navigate(['/Subscription', {fName: firstName, lName: //lastName, email: email}]);
确保 this.registerForm.value 是 JSON 格式。在 subscriptioncomponent 中,你可以像下面这样从 URL 获取所需的值
this.route.paramMap.subscribe(
params => {
this.fName = params.get('fName');
this.lName = params.get('lName');
this.email = params.get('email');
});
