Dynamic form in angular 2 can it be done?


I would like to ask you if you know if it is possible in the angular technology 2, to make a form, that some compos validate in function of another capmo as for example a checkbox that when true its value activates the validation of other two inputs. / p>

Thank you

asked by Pekée 11.01.2017 в 08:51

3 answers


If you can, check this official documentation:

Form validation in Angular2

You could launch a function in the ngModelChange directive that changes the variable you need and in the validation condition the queries to act in one way or another.

You already tell us. Greetings.

answered by 11.01.2017 в 11:44

If possible, it depends on what you need in your form, you can use ng-change for checkbox and ng-show or ng-if in the input. This could be the checkbox code and the input ...

        <input type="checkbox" ng-model="activo" ng-change="activar()">
        <input type="text" ng-show="activarInput" name="input1">
        <input type="text" ng-show="activarInput" name="input2">

Here you can define an initial value of the checkbox, by default we will leave it in false, in the controller we would have the following.

        var app = angular.module("app", [])
        app.controller("appCtrl", function(){
             $scope.activo = false;
             //lo sigiente activa o desactiva los input
             //suponiendo que se activen los dos al mismo tiempo
             $scope.activarInput = false;
             $scope.activar = function(){
                   $scope.activo = true;
                   $scope.activarInput = true;

I hope this is what you need, regards.

answered by 11.01.2017 в 17:48

I was able to find the answer I needed. In the end what I find, is to subscribe to the ngModelChange event of the checkbox in question and with the following code I add the validators or the group sack.

onEsRegalChanged(value: any) {
        //Posar i treure els validadors en funcio del valor del checkbox;
        if (!value) {
        } else {


But it must be a FormControl necessarily to put validators!

answered by 16.01.2017 в 11:36