Angular 5中如何从一个组件修改另一个组件的变量
Hey there! As someone who’s navigated the Angular learning curve before, let’s break down your component code and help you nail that simple logic you’re working on. First, let’s get your code formatted clearly so we can see exactly what we’re working with:
sidebar.component.ts
import { Component, OnInit, Input } from '@angular/core'; import { FormComponent } from 'app/form/form.component'; @Component({ selector: 'app-sidebar', templateUrl: './sidebar.component.html', styleUrls: ['./sidebar.component.css'] }) export class SidebarComponent implements OnInit { public serverStatus1: boolean = false; public serverStatus2: boolean = false; s1: number; s2: number = 0; ngOnInit(): void { // This is where your initialization logic will live // Examples: Setting initial values, fetching data, or subscribing to observables } }
Now, let’s go over some key tips to help you implement your desired logic smoothly:
Clean Up Variable Initialization: I added a return type (
: void) tongOnInitand standardized spacing—consistent formatting makes debugging way easier later on. Yours1variable is declared but not initialized; if you don’t plan to set it immediately, consider giving it a default value (likes1: number = 0;) or marking it as optional with?(e.g.,s1?: number).Leverage
@Input()Properly: You importedInputbut aren’t using it yet. If you need to pass data from a parent component to this sidebar, add something like@Input() parentData: string;inside the class. This is a core Angular pattern for dynamic, reusable components.Toggle UI with Server Statuses: Your
serverStatus1andserverStatus2booleans are perfect for conditional UI rendering. In yoursidebar.component.html, use Angular’s*ngIfto show/hide elements based on these statuses:<div *ngIf="serverStatus1" class="status-indicator online">Server 1 is active!</div> <div *ngIf="serverStatus2" class="status-indicator online">Server 2 is active!</div>Avoid Tight Component Coupling: You imported
FormComponentbut aren’t using it here. If you need to communicate with the form component, use a shared service instead of direct imports—Angular’s dependency injection is built for clean, decoupled component interactions.
If you share more details about the specific logic you want to build (like toggling statuses on user clicks, updating s1/s2 values, or syncing with the form component), we can dive even deeper!
内容的提问来源于stack exchange,提问作者David Cring

