在Angular 6中,在命名的次要路由插槽中使用查询参数,可以通过修改路由配置和组件代码来实现。
首先,在路由配置中定义一个次要路由插槽,并指定它的组件和路径,同时添加一个查询参数:
const routes: Routes = [
{ path: 'main', component: MainComponent },
{ path: 'secondary', component: SecondaryComponent, outlet: 'secondary', pathMatch: 'full' },
{ path: 'secondary/:param', component: SecondaryComponent, outlet: 'secondary', pathMatch: 'full' }
];
在上面的代码中,我们定义了两个次要路由路径,一个是没有查询参数的路径,另一个是带有参数的路径。
接下来,我们需要在组件中获取查询参数。在次要路由组件中,使用ActivatedRoute来获取查询参数:
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-secondary',
templateUrl: './secondary.component.html',
styleUrls: ['./secondary.component.css']
})
export class SecondaryComponent implements OnInit {
param: string;
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route.params.subscribe(params => {
this.param = params['param'];
});
}
}
在上面的代码中,我们使用ActivatedRoute来订阅路由参数,并将参数赋值给组件的param属性。
最后,在次要路由插槽中使用查询参数,可以在模板中使用{{ param }}来显示查询参数的值:
Secondary Component
Param: {{ param }}
这样,当你在次要路由中使用查询参数时,查询参数的值将显示在页面上。