英文:
<select> not redirecting to a url
问题
我正在尝试让我的选择标签将我重定向到option
值中的URL。例如,这是我的代码:
<select #selectElement (change)="redirectToUrl(selectElement.value)">
<option value="/add-product">Add a product</option>
</select>
在.component.ts文件中:
@ViewChild('selectElement', { static: false })
selectElement!: ElementRef;
redirectToUrl(url: String) {
if (url){
const urlTree: UrlTree = this.router.createUrlTree([url]);
this.router.navigateByUrl(urlTree);
}
}
当我选择选项时,什么都不会发生。我不知道我漏掉了什么...
英文:
I'm trying to get my select tag to redirect me to a url that is in option
value. For example this is my code:
<select #selectElement (change)="redirectToUrl(selectElement.value)">
<option value="/add-product">Add a product</option>
</select>
And in .component.ts is:
@ViewChild('selectElement', { static: false })
selectElement!: ElementRef;
redirectToUrl(url: String) {
if (url){
const urlTree: UrlTree = this.router.createUrlTree();
this.router.navigateByUrl(urlTree);
}
}
And ofc, when I select the option, nothing happens. I don't know what I'm missing...
答案1
得分: 1
With only one option the change event will never fire, as the option is selected by default. You can add a null option as a kind of placeholder when using a formControl that is preset to null
:
<select [formControl]="urlSelect">
<option [value]="null" disabled>Please select</option>
<option value="/add-product">Add a product</option>
</select>
public urlSelect = new FormControl<string | null>(null);
public ngOnInit(): void {
this.urlSelect.valueChanges.subscribe((url) => {
if (url) {
const urlTree: UrlTree = this.router.createUrlTree([url]);
this.router.navigateByUrl(urlTree);
}
});
}
You need to import FormsModule for this to work, and you should make sure to unsubscribe from urlSelect.valueChanges
when the component is destroyed.
英文:
With only one option the change event will never fire, as the option is selected by default. You can add a null option as a kind of placeholder when using a formControl that is preset to null
:
<select [formControl]="urlSelect">
<option [value]="null" disabled>Please select</option>
<option value="/add-product">Add a product</option>
</select>
public urlSelect = new FormControl<string | null>(null);
public ngOnInit(): void {
this.urlSelect.valueChanges.subscribe((url) => {
if (url) {
const urlTree: UrlTree = this.router.createUrlTree([url]);
this.router.navigateByUrl(urlTree);
}
});
}
You need to import FormsModule for this to work, and you should make sure to unsubscribe from urlSelect.valueChanges
when the component is destroyed.
答案2
得分: 0
重定向到网址(url: 字符串) {
如果 (url) this.router.navigateByUrl(url);
}
或
重定向到网址(url: 字符串) {
如果 (url)
this.router.navigate();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论