I am working on an Angular project that needs to display different forms on each page using Angular routing, but since the forms will likely be very similar I was planning on just having a component that I would pass props to
Ie, have a Form
component and a json file with all the questions like form1.json
that would be used to autogenerate a front end
<Form questions="./form1.json" />
<Form questions="./form2.json" />
<Form questions="./form3.json" />
I know how to use routing to create a new route for a singular component like this:
const routes: Routes = [
{ path: 'form', component: Form }
];
However, this just creates a route for the Form component at "www.formwebsite.com/form"
but I was wondering if it was possible to create a new route for each time I called the component AND make the route have a url specified by data passed into the component?
IE doing <Form questions="./form1.json" />
would appear as "www.formwebsite.com/form1", and doing <Form questions="./form2.json" />
would appear on a seperate route as "www.formwebsite.com/form2"
I'm pretty new to both Angular and this is my first time posting on stack overflow so if the post is confusing or doesn't include detail please comment and I'll specify stuff or add more info
CodePudding user response:
To have your routes change name like youre wanting change your routing to:
const routes: Routes = [
{ path: '/:formName', component: Form }
];
That syntax will allow you to have 'dynamic' url names. Within your Form component you can get which formName it is by doing this:
...
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.params.subscribe((params: Params) => {
console.log(params.formName); // same as :formName in route
});
// or
console.log(this.route.snapshot.paramMap.get('formName'));
}
Side note: Make sure you research angular routing navigation. docs If you structure your navigation wrong it may result in a headache.
Another sidenote: You might look into Angular Reactive forms which allow for fantastic form validation: form docs