使用被动形式Angular实时获取复选框值

时间:2017-07-12 22:24:32

标签: forms angular angular-reactive-forms

我有一个国家/地区对象列表,我可以访问并使用我的被动表单。我动态地创建每个表单控件,因为这个列表将会改变。然后我尝试通过使用ngOnChanges钩子实时获取表单和值(不使用提交按钮),因为单击复选框。这显然不起作用,我应该使用什么钩子?另一方面,这是一个不好的方法吗?什么是更好的方法?

成分<​​/ P>

export class GeoDropComponent implements OnInit, OnChanges {
    countries = [
        {
            name : 'USA',
            continent : 'north america'
        },
        {
            name : 'Canada',
            continent: 'north america'
        }
    ];

    countriesForm: FormGroup;

    constructor() { }

    ngOnInit() {
        // add checkbox for each country
        this.countriesForm = new FormGroup({});
        for (let i = 0; i < this.countries.length; i++) {
            this.countriesForm.addControl(
                this.countries[i].name, new FormControl(false)
            )
        }
    }

    ngOnChanges() {
        console.log(this.countriesForm);
    }

}

HTML

<div class="geo-list">
    <div class="content-box container">
        <form [formGroup]="countriesForm">
            <div class="country" *ngFor="let country of countries">
                <input
                    type="checkbox"
                    formControlName="{{country.name}}"
                >
                {{ country.name }} | {{ country.continent }}
            </div>
        </form>
    </div>
</div>

1 个答案:

答案 0 :(得分:1)

你可以这样试试。当选择或选择搜索复选框时,更改方法将更新所选项目

伪代码

"dependencies": {
    "lodash": "^4.17.4",
    "native-base": "^2.2.1",
    "react": "16.0.0-alpha.12",
    "react-native": "0.46.1",
    "react-native-firebase": "^2.0.2",
    "react-native-navigation": "^1.1.134",
    "react-redux": "^5.0.5",
    "redux": "^3.7.1",
    "redux-orm": "^0.9.4",
    "redux-persist": "^4.8.2",
    "redux-thunk": "^2.2.0"
  },
  "devDependencies": {
    "babel-jest": "20.0.3",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react-native": "2.1.0",
    "babel-preset-stage-2": "^6.24.1",
    "jest": "20.0.4",
    "react-test-renderer": "16.0.0-alpha.12",
    "redux-immutable-state-invariant": "^2.0.0",
    "redux-logger": "^3.0.6",
    "redux-orm-proptypes": "^0.1.0"
  },

组件文件。

{
  "plugins": ["transform-runtime"],
  "presets": ["react-native"]
}