Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 默认情况下,如何使*ngFor中的第一项处于活动状态?_Arrays_Angular_Components_Ngfor - Fatal编程技术网

Arrays 默认情况下,如何使*ngFor中的第一项处于活动状态?

Arrays 默认情况下,如何使*ngFor中的第一项处于活动状态?,arrays,angular,components,ngfor,Arrays,Angular,Components,Ngfor,我在Angular 2中有一个单选按钮组件 <div class="states" *ngFor="let state of states; let i = index" [ngClass]="{'selected': showElement === state}" (click)="trackCurrentState(state)"> <div class="radio"> <div class="outsi

我在Angular 2中有一个单选按钮组件

<div
    class="states"
    *ngFor="let state of states; let i = index"
    [ngClass]="{'selected': showElement === state}"
    (click)="trackCurrentState(state)">
    <div class="radio">
        <div class="outside">
            <div
                class="inside"
                *ngIf="showElement === state">
            </div>
        </div>
    </div>
    <p2>{{state.name}}</p2>
</div>

{{state.name}

*ngFor循环通过它们,并在另一个组件中显示它们。加载时,我的变量“showElement”返回未定义,直到用户单击其中一个单选按钮。因此,在加载时,我有一组单选按钮,但在用户单击一个按钮之前,没有一个按钮被选中。我希望默认情况下选择单选按钮组中的第一个按钮(对象数组中的第一项)。我需要将我的类“inside”应用于第一个单选按钮,直到用户单击另一个单选按钮。我怎样才能做到这一点呢?

如果我猜对了你需要什么,那就是:

  this.showElement = this.states[0]
要为所选选项提供“内部”类,只需使用:

<div [class.inside]="showElement"> </div>

在构造函数中或ngOnInit上,ngAfterViewInit-取决于您初始化this.showElement和this.states的位置

我认为您应该与“state”发生名称冲突,我在尝试创建plunker时看到了这一点
 this.showElement = this.states[0];