我的Angular2应用程序包含3个选项组的下拉元素,如下所示:
([0-9]{2,6})\1
我将此片段添加到每个选项组,以将元素置于当前值:
<select formControlName="reasonCode" id="reasonCode" class="form-control">
<option value="" [ngValue]="null"></option>
<option *ngFor="let reason of otherLeavingReasons" [ngValue]="reason.longName">
{{reason.longValue}}
</option>
<optgroup label="Managed">
<option *ngFor="let reason of managedLeavingReasons" [ngValue]="reason.longName">
{{reason.longValue}}
</option>
</optgroup>
<optgroup label="Unmanaged">
<option *ngFor="let reason of unmanagedLeavingReasons" [ngValue]="reason.longName">
{{reason.longValue}}
</option>
</optgroup>
</select>
问题在于它不起作用。我怀疑是因为存在3个选项组。 有没有其他方法可以做到这一点,或者可能是不同的组件能够在单一选项组中持有这些组?
答案 0 :(得分:3)
您使用的是ReactiveModule
表单。在此表单中,您不需要在每个[selected]
中设置option
。即使您永远也不需要设置[selected]
属性来添加设置为已选择。只需设置模型值,您就会更新您的UI。
在您的代码中将此代码放在component
this.form.controls['reasonCode'].patchValue("myvalue");
答案 1 :(得分:1)
我最后通过跟踪和错误方法对它进行了排序。它像[ngValue]和[selected]一样,不能一起使用,或者至少在我的应用程序中使用。当我删除[ngValue]时,选择开始起作用。 它并不意味着它是最终的和推荐的解决方案,但它适用于这种情况。所以最终的工作代码如下所示:
...
replace: false,
transclude: false,
compile: function( tElement, tAttributes ) {
// store your "transcluded" content of the directive in the variable
var htmlContent = tElement.html();
// then remove it
tElement.html('');
return function postLink(scope, elem, attrs) {
// then html var is available in your link!
var $html = $('<div />',{ html:htmlContent }); // for much easier manipulation (so you can use DOM functions - you can also manipulate directly on htmlContent string)
// so you can manipulate the content however you want
scope.myVariable = true;
$html.find('li').attr('ng-hide', 'myVariable'); // add native directive
$html.removeClass('inner-content').addClass('my-inner-content'); // add/remove class
$html.find('#myElement').attr('my-directive',''); // add custom directive etc. etc.
// after you finished you just need to compile your html and append your directive element - also however you want
// you also convert back $html to the string
elem.append( $compile( $html.html() )(scope) ); // append at the end of element
/* or:
elem.find('.my-insert-point').html( $compile( $html.html() )(scope) ); // append the directive in the specific point
elem.find('[my-transclude]').html( $compile( $html.html() )($parent.scope) ); // once the scope:true it will be the same as native transclusion ;-)
scope.variable = $html.html(); // or you can probably assign to variable and use in your template with bind-html-compile (https://github.com/incuna/angular-bind-html-compile) - may need $sce.trustAsHtml
*/
}
}
...