如何自动获取URL参数到HTML字段angular 5
How to get URL parameter to HTML field automatically angular 5
这里我想将这个 URL 参数自动添加到 Angular 的入学编号字段 5. 请帮助我。怎么做?
您的组件应如下所示:
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'foo',
template: '<input type="text" [value]="admissionNo">'
...
})
export class FooComponent implements OnInit {
admissionNo: string;
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route.queryParams
.subscribe(params => this.admissionNo = params.admission_no || '');
}
}
您必须注入 ActivatedRoute
和 Params
。然后您可以通过 Subscription
;
访问该值
TS代码
import {Router, ActivatedRoute, Params} from '@angular/router';
import {OnInit, Component} from '@angular/core';
@Component({...})
export class MyComponent implements OnInit {
admission_no: string;
constructor(private activatedRoute: ActivatedRoute) {}
ngOnInit() {
// Note: Below 'queryParams' can be replaced with 'params' depending on your requirements
this.activatedRoute.queryParams.subscribe(params => {
this.admission_no = params['admission_no'];
console.log(admission_no);
});
}
}
然后在你的HTML中通过插值做这样的事情:
<input name="admission_no" [(ngModel)]="admission_no">
这里我想将这个 URL 参数自动添加到 Angular 的入学编号字段 5. 请帮助我。怎么做?
您的组件应如下所示:
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'foo',
template: '<input type="text" [value]="admissionNo">'
...
})
export class FooComponent implements OnInit {
admissionNo: string;
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route.queryParams
.subscribe(params => this.admissionNo = params.admission_no || '');
}
}
您必须注入 ActivatedRoute
和 Params
。然后您可以通过 Subscription
;
TS代码
import {Router, ActivatedRoute, Params} from '@angular/router';
import {OnInit, Component} from '@angular/core';
@Component({...})
export class MyComponent implements OnInit {
admission_no: string;
constructor(private activatedRoute: ActivatedRoute) {}
ngOnInit() {
// Note: Below 'queryParams' can be replaced with 'params' depending on your requirements
this.activatedRoute.queryParams.subscribe(params => {
this.admission_no = params['admission_no'];
console.log(admission_no);
});
}
}
然后在你的HTML中通过插值做这样的事情:
<input name="admission_no" [(ngModel)]="admission_no">