单击按钮时Angular2输入数据丢失

时间:2016-11-03 16:13:54

标签: angular input

我已经创建了像这样的Angular2代码来获取按钮上的数据

class Example extends React.Component
{
    constructor(props){
        super(props);
        this._handleInputChange = this._handleInputChange.bind(this);
        this._submitHandler = this._submitHandler.bind(this);
        this._resetHandler = this._resetHandler.bind(this);
        this._setInitialState = this._setInitialState.bind(this);
        this.state = this._setInitialState();
    }
    _resetHandler(){
        this.setState((prevState, props) => {
            var newState = {};
            for( var key in prevState ) {
                if ( prevState.hasOwnProperty(key) ) {
                    newState[key] = undefined;
                }
            }
            if( typeof this._setInitialState === 'function' ){
                Object.assign(newState, this._setInitialState());
            }
            return newState;
        });
    }

    _setInitialState(){
            return {
                mode: 'advanced',
                created: {},
                changed: {}
            };
    }

    _handleInputChange(){
        // do stuff to change the state
    }
}

但是当单击该按钮时,输入字段上的数据将在ui中丢失。如何在单击按钮时保持它并在ui上显示?

1 个答案:

答案 0 :(得分:1)

我猜测您在表单中工作,因此请将type="button"添加到按钮<button class="btn btn-success" (click)="addData(newData.value)">ADD</button>。这应该可以防止它认为表单正在提交和清除数据。