Dynamic checkboxes

Asked

Viewed 23 times

1

I am wanting to create dynamic checkboxes. This code should give me, in the field categories, an object with 3 items false, but it’s not working. Where am I going wrong?

export class FormPostsComponent implements OnInit {

    form: FormGroup;

    constructor(
        private categoriesService: CategoriesService,
        private formBuilder: FormBuilder
    ) { }

    ngOnInit() {

        this.form = this.formBuilder.group({
            id: [null],
            title: [null, [Validators.required, Validators.minLength(3)]],
            body: [null, [Validators.required]],
            categories: this.buildCategories(),
            tags: [null],
            imgFeatured: [null],
            slug: [null]
        });
    }

    buildCategories() {

        const values = this.categoriesService.read().subscribe(
            categories => categories.map(
                x => new FormControl(false)
                )
            )
        return this.formBuilder.group(values);
    }
}

1 answer

0

The error occurs because subscribe does not return categories, it only serves to take the request data and keep it within the scope if the value is not assigned to a variable. You can make the following change to add categories to this set.

export class FormPostsComponent implements OnInit {

    form: FormGroup;

    constructor(
        private categoriesService: CategoriesService,
        private formBuilder: FormBuilder
    ) { }

    ngOnInit() {

        this.form = this.formBuilder.group({
            id: [null],
            title: [null, [Validators.required, Validators.minLength(3)]],
            body: [null, [Validators.required]],
            categories: this.formBuilder.group({}),
            tags: [null],
            imgFeatured: [null],
            slug: [null]
        });

        this.buildCategories();

    }

    buildCategories() {

        this.categoriesService.read().subscribe(
            categories => categories.map(
                category => this.form.get('categories').addControl(false)
            )
        );

    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.