Skip to content

component structure

Raphaël Balet edited this page Dec 6, 2023 · 12 revisions

my.component.ts

Example on how the component.ts should be structured.

Note: The order have to be respected

@component{(
  selector: 'my-component',
  templateUrl: 'my-component.html',
  styleUrls: ['my-component.scss'], // Only if scss contains code
)}
export class myComponent extends baseComponent implements ngOnInit {
  @ViewChild('myChild', {red: ViewContainerRef})

  @Input() myInput: any

  private _myInput: any
  @Input() set myInput(value: any) {
    this._myInput = value
  }
  get myInput() {
    return this._myInput
  }
  
  @Output() myOutput: any

  mySignal$ = Signal<any>() // $ for signal
  myObservable$: Observable // $ for observable

  myPublicVar: any // single variable (object/number/string/boolean)
  myPublicVars: any[] // s -> arrays of something

  myBoolean = false // don't give a type if you directly assign a value
  myBoolean: boolean = false // Bad
  myObjects: User[] = [] // Good : because we don't know what kind of object we declare

  protected _myProtectedVar: any // _ for protected

  private _myPublicVar: any // _ for private

  constructor(
    public publicClass: PublicClass,
    protected readonly _protectedClass: ProtectedClass,
    private readonly _privateClass: PrivateClass,
    _config: heritedClass
  ) {
    super(_protectedClass, _config)
    this._privateClass.doSomething() // use "this" when calling a class / variable
  }

  // 1: angular lifecycle hooks -> https://angular.io/guide/lifecycle-hooks
  ngOnInit() { // Angular methods Should be implemented at the class lvl

  }

  // 2: public methods
  publicMethod() {

  }

  // 2.2 : If the method uses another one from the same class, it should be placed under this one
  secondPublicMethod() {
    /**
    * do something
    */
    this.publicMethod().doSomething()
  }

  // 3: protected methods (notice, methods should be grouped first by functionality and then per access level)
  protected protectedMethod() {

  }

  // 4: private methods
  private privateMethod() {

  }

}

Methods

Variables

If a class only has one element (ex: user),

  • attributes: For a single user
  • items: for an array of users.
  • Methods have general purpose name
    • Good: getAttributes()
    • Bad: getUser()

Service

If you're using one single service for the component, use general service as name

Example

attributes: user
items: user[]

constructor(public service: ComponentService) {}

getAttributes(): any {}  // return a single object/variable

getItems(): any[] {}  // s -> return an array of

// set a value
setAttributes(id: number): void {
  this.attributes = id
}

// populating an arrays
populateItems(objects: any[]): void {
  const items = []

  this.objects.foreach(object => {
    items.push(object)
  })

  this.items = items
}

deleteItem() {}

updateItem() {}


toggleTheme() {
  this.myBoolean = !this.myBoolean
}

Clone this wiki locally