【问题标题】:How to initialize the value of an input[range] using Angular2 when value is over 100当值超过100时如何使用Angular2初始化输入[范围]的值
【发布时间】:2016-12-12 22:17:42
【问题描述】:

我在使用 AngularJS 时遇到过这种情况,这就是 How to initialize the value of an input[range] using AngularJS when value is over 100 发帖的原因。
我想知道 Angular2 可以更好地初始化默认范围 [0,100] 和 [min,max] 范围内的值。

我构建的尝试学习 Angular2 的代码几乎是对上一篇文章的翻译:

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.17/angular2-polyfills.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.17/Rx.umd.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.17/angular2-all.umd.min.js"></script>

<script>
(function (app) {
    app.AppComponent = ng.core.Component({
	    selector: 'my-app',
	    template: '	{{ctrl.min}}<input type="range" [(ngModel)]="ctrl.value" min="{{ctrl.min}}" max="{{ctrl.max}}" />{{ctrl.max}}<br/>value:{{ctrl.value}}'
	})
	.Class({
	    constructor: function() {
		  this.ctrl = { min:50, max:150, value:150};
	    }
	});
})(window.app || (window.app = {}));

(function (app) {
	document.addEventListener('DOMContentLoaded', function () {
	   ng.platform.browser.bootstrap(app.AppComponent);
	});
})(window.app || (window.app = {}));
</script>
 
</head>
<body>
   <my-app>Loading...</my-app>
</body>
</html>

运行这个 sn-p 得到这个结果:

滑块在位置 100,但它应该在位置 150。 预期结果是:

有没有办法一致地设置 3 个值(最小值、最大值和值),而不受值 [0,100] 的限制?

是否可以在初始化范围之后和设置初始值之前更新 DOM?

【问题讨论】:

    标签: javascript input angular range


    【解决方案1】:

    我最喜欢这样确定排序的方式(不知道它是否正确),就是简单地用setTimeout 推迟它。

      constructor() {
            this.min = 50;
            this.max = 150;
            setTimeout(() => this.value = 150);
      }
    

    您不需要设置实际的计时值。这将确保 this.value 在下一个更改检测周期之前未设置。

    See here for a live demo.

    【讨论】:

    • 我想过这个问题,但是当我进行了一个 AJAX 调用时,它会得到一个 JSON 列表“min”、“value”、“max”。这需要专门解析值来引入这个延迟设置。
    • @mpromonet 这如何改变事情? `http.get('/foo').subscribe((res) => { this.min = res.min; this max = res.max; setTimeout(() => this.value = res.value); } )
    • 我尝试使用http.get('/controls').subscribe(function(data) { this.controlList = data.json(); }*ngFor="let control of controlList" 来迭代控件数组。您的解决方案需要额外的代码来存储 http 答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    • 2015-12-05
    • 1970-01-01
    相关资源
    最近更新 更多